I am getting a bit of headache just because a simple looking, easy statement is throwing some errors in my face.
I have a json file called strings.json like this:
In python 3, we can use below method.
Read from file and convert to JSON
import json
from pprint import pprint
# Considering "json_list.json" is a json file
with open('json_list.json') as fd:
json_data = json.load(fd)
pprint(json_data)
with statement automatically close the opened file descriptor.
String to JSON
import json
from pprint import pprint
json_data = json.loads('{"name" : "myName", "age":24}')
pprint(json_data)
To add on this, today you are able to use pandas to import json:
https://pandas.pydata.org/pandas-docs/stable/generated/pandas.read_json.html
You may want to do a careful use of the orient parameter.
The problem is using with statement:
with open('strings.json') as json_data:
d = json.load(json_data)
pprint(d)
The file is going to be implicitly closed already. There is no need to call json_data.close()
again.
This works for me.
json.load() accepts file object, parses the JSON data, populates a Python dictionary with the data and returns it back to you.
Suppose JSON file is like this:
{
"emp_details":[
{
"emp_name":"John",
"emp_emailId":"john@gmail.com"
},
{
"emp_name":"Aditya",
"emp_emailId":"adityatest@yahoo.com"
}
]
}
import json
# Opening JSON file
f = open('data.json',)
# returns JSON object as
# a dictionary
data = json.load(f)
# Iterating through the json
# list
for i in data['emp_details']:
print(i)
# Closing file
f.close()
#Output:
{'emp_name':'John','emp_emailId':'john@gmail.com'}
{'emp_name':'Aditya','emp_emailId':'adityatest@yahoo.com'}
You can use pandas library to read the JSON file.
import pandas as pd
df = pd.read_json('strings.json',lines=True)
print(df)
The json.load() method (without "s" in "load") can read a file directly:
import json
with open('strings.json') as f:
d = json.load(f)
print(d)
You were using the json.loads() method, which is used for string arguments only.
Edit: The new message is a totally different problem. In that case, there is some invalid json in that file. For that, I would recommend running the file through a json validator.
There are also solutions for fixing json like for example How do I automatically fix an invalid JSON string?.