Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading