saving a JSON file in python

Question:

I have made some changes to a JSON file in python by using numpy and pandas. I have successfully made the desired changes as I can see through print() function, but I am unable to save the changes as a new file with .json extension. The code is given as below.

df = pd.read_json("file_name.json")
result = df.to_json(orient='records')
parsed = json.loads(result)
json_out = json.dumps(parsed, indent=4)
print(json_out)
Asked By: Khan

||

Answers:

It would have been better if you had shared the structure of the JSON file with us.

I will work with a hypothetical format in this case:

import json

# dummy JSON format
data = {
'employees' : [
    {
        'name' : 'John Doe',
        'department' : 'Marketing',
        'place' : 'Remote'
    },
    {
        'name' : 'Jane Doe',
        'department' : 'Software Engineering',
        'place' : 'Remote'
    },
    {
        'name' : 'Don Joe',
        'department' : 'Software Engineering',
        'place' : 'Office'
    }
 ]
}

json_string = json.dumps(data)

If you format of your JSON is such as above we can save the JSON into a file by:

# Directly from the dictionary
with open('json_data.json', 'w') as outfile:
    json.dump(data, outfile)

# Using a JSON string
with open('json_data.json', 'w') as outfile:
    outfile.write(json_string)

Reference:

  1. https://stackabuse.com/reading-and-writing-json-to-a-file-in-python/
Answered By: Sahaj Raj Malla
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.