Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove &q; and load string using json.loads function

Tags:

python

json

I am trying to load below json string using json.loads function in python. but &q; is not a valid json object.

Is there a way for me to remove this? I've provided a sample below:

[{&q;Id&q;:1,&q;Name&q;:&q;Name}]
like image 246
Awaish Kumar Avatar asked Aug 04 '26 04:08

Awaish Kumar


2 Answers

Angular uses a special escapeHtml function for transfer state. You can find those escapeHtml/unescapeHtml functions here:

export function escapeHtml(text: string): string {
  const escapedText: {[k: string]: string} = {
    '&': '&a;',
    '"': '&q;',
    '\'': '&s;',
    '<': '&l;',
    '>': '&g;',
  };
  return text.replace(/[&"'<>]/g, s => escapedText[s]);
}

export function unescapeHtml(text: string): string {
  const unescapedText: {[k: string]: string} = {
    '&a;': '&',
    '&q;': '"',
    '&s;': '\'',
    '&l;': '<',
    '&g;': '>',
  };
  return text.replace(/&[^;]+;/g, s => unescapedText[s]);
}

You can reproduce this escape function in python using the following code:

import json

unescapedText = {
    '&a;': '&',
    '&q;': '"',
    '&s;': '\'',
    '&l;': '<',
    '&g;': '>',
}

def unescape(str):
    for key, value in unescapedText.items():
        str = str.replace(key, value)
    return str

state = "[{&q;Id&q;:1,&q;Name&q;:&q;Name&q;}]"
decoded = json.loads(unescape(state))

print(decoded)

repl.it: https://replit.com/@bertrandmartel/AngularTransferStateDecode2

like image 98
Bertrand Martel Avatar answered Aug 05 '26 20:08

Bertrand Martel


try simple to replace the &q; with " double quotes

import json
data = '[{&q;Id&q;:1,&q;Name&q;:&q;Name&q;}]'
data = data.replace('&q;', '"')
print(json.loads(data))

Output

[{'Id': 1, 'Name': 'Name'}]
like image 31
Druta Ruslan Avatar answered Aug 05 '26 20:08

Druta Ruslan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!