Ayaz Ahmad Tarar Ayaz Ahmad Tarar - 1 year ago 126
JSON Question

string is a JSON object or JSON array in Python?

I am reading JSON file line by line. Few lines contain JSON objects while other contains JSON array. I am using

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_array = []
for obj in json_file:
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.

Answer Source

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
isintance(obj, list)

# if returns true, then JSON Object.
isintance(obj, dict)
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download