Reputation: 1
I'm new to Json and Python and have been trying to update a Json file, I'm struggling with the process to read, update and save the file with the old and new information. I try it using only Json Strings but had a lot of problems with the format and I prefer to read the Json to a Pandas Dataframe, update and then save it. I am able to save and update the dataframe, but have problems reading the file to the Dataframe.
Everything is working fine except the read_json function:
df = df.read_json("registryDB.json")
I am getting this error:
AttributeError: 'DataFrame' object has no attribute 'read_json'
This is the function code:
df = df.read_json("registryDB.json")
df = df.append({
'Name': 'John',
'User': 'John123',
'Last Name': 'Doe',
'Age': 27,
'Gender': 'm',
'Location': 'US',
'Date': timestamp
}, ignore_index=True)
file = df.to_json(orient='table')
with open("registryDB.json", "w") as dataFile:
json.dump(file, dataFile)
I don't know if this is the best or correct way of doing this, so if you know any other, any advise would be awesome.
Thank you!
Upvotes: 0
Views: 630
Reputation: 3554
AttributeError
The .read_json
function is a function in pandas
and not a method on a pandas.DataFrame
object. Therefore you'll need to call it like so:
import pandas as pd
df = pd.read_json("registryDB.json")
You are creating the df
by calling the pandas
read_json()
function.
In Python, there's an easier way to interact with JSON: the json
module that is part of Python's standard library.
You can quickly read in a JSON file to a Python dictionary. Then you can work with it just like any Python dictionary. When you're ready to save it back to a JSON file, it's another straightforward call:
import json
with open("registryDB.json", "r") as fin:
data = json.load(fin)
# do your edits on the data dict
with open("new_file.json", "w") as fout:
json.dump(data, fout)
Upvotes: 1