Convert python dictionary into JavaScript json object and add to js file

Advertisements

I have a js file abc.js containing a JSON object as below:

export default{
"Name": "James",
"Age": "21"
}

I have a python dictionary dict with the value:

{"Country":"Italy"}

How can I append dict to abc.js such that it becomes:

export default{

"Name": "James",
"Age": "21",
"Country":"Italy"
}

I tried the below approach:

with open("abc.js", "w") as file:
    json.dump(dict, file)

I’m aware that this will replace the whole file but is there any way to append while also keeping the export default{} ?

>Solution :

Remove export default when reading the file, and add it back when writing.

with open("abc.js") as f:
    contents = f.read()

contents = contents.replace('export default', '')
data = json.loads(contents)
data['Country'] = 'Italy'
new_contents = 'export default' + json.dumps(data)

with open("abc.js", "w") as f:
    f.write(new_contents)

Leave a ReplyCancel reply