I am reading JSON file line by line. Few lines contain JSON objects while other contains JSON array. I am using json.loads(line) function to get JSON from each line.
def read_json_file(file_name):
json_file = []
with open(file_name) as f:
for line in f:
json_file.append((line))
json_array = []
for obj in json_file:
try:
json_array.append(json.loads(obj))
except ValueError:
print("data was not valid JSON")
return json_array
Is there any way that I can find out that object I am reading is JSON Object or JSON array? I want to save all the result in json_array.
I will be thankful to you if anyone can help me.
In python, JSON object is converted into dict and JSON list is converted into list datatypes.
So, if you want to check the line content which should be valid JSON, is JSON Object or JSON Array, then this code will helps you:-
import json
# assume that, each line is valid json data
obj = json.loads(line)
# if returns true, then JSON Array
isinstance(obj, list)
# if returns true, then JSON Object.
isinstance(obj, dict)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With