skip to Main Content

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{} ?

2

Answers


  1. 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)
    
    Login or Signup to reply.
  2. You can also extract JSON data from your js file, merge it with your Python dictionary, and write it back to the file.

    import json
    with open("abc.js","r") as file:
        contents = file.read()
    json_object = json.loads(contents[contents.index("{"):])
    countries = {"Country":"Italy"}
    
    merged_object = {**json_object, **countries}
    
    with open("abc.js","w") as file:
        file.write("export default " + json.dumps(merged_object, indent = 4))
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search