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)
CodePudding user response:
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(json_string, outfile)
# Using a JSON string
with open('json_data.json', 'w') as outfile:
outfile.write(json_string)
Reference: