I have been fighting with this problem for a few weeks now and still cannot understand what's wrong here.
I created a dictionary in python dic
. Then I am using dumps to convert it to a valid json.
json_js = json.dumps(dic) # works fine, a valid json from the python's viewpoint
# the reverse operation works fine also
dic = json.loads(json_js)
print(json_js)
==============
{"p0": {"pf": {"id": "pf1", "class": ["pf", "w0", "h0"], "data-page-no": "1"}, "pc": {"class": ["pc", "pc1", "w0", "h0"]}, "img": ["<img alt=\"\" clas
This json_js I use later on to add it to a js script that applies JSON.parse()
on it. And this is the error that I get.
SyntaxError: JSON.parse: expected ',' or ']' after array element at line 1 column 143 of the JSON data
That 143 character is the first \"
. But why can't js figure it as a valid JSON I cannot comprehend.
Would you have any suggestions what might have gone wrong here?
EDIT.
No idea why people close my question. The desired behaviour is that JSON.parse
doesn't throw any errors. The way how I added it to a script is irrelevant for the question. Please, have a look at the part of the source code inside html .
const str = `{"p0": {"pf": {"id": "pf1f", "class": ["pf", "w2", "h2"], "data-page-no": "1f"}, "pc": {"class": ["pc", "pc1f", "w2", "h2"]}, "img": ["<img alt=\"\" class=\"bi x0 y0 w1 h1\"` // this string is several megabytes so I only put the first 150 or so characters here.
var dic = JSON.parse(str);
EDIT 2. The full transformation.
# in python using BeautifulSoup for scripts and new_html
new_html = bs()
dom = bs()
scripts = [dom.new_tag('script')]
scripts[0].string = html_script(json_js) # html_script is a "string... %s" %json_js
new_html.body.append(scripts[0])
with open('stuff.html','w',encoding='utf-8') as f:
f.write(str(new_html))