Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 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.

like image 848
Ayaz Ahmad Tarar Avatar asked Oct 29 '25 03:10

Ayaz Ahmad Tarar


1 Answers

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)
like image 195
Akshay Pratap Singh Avatar answered Oct 31 '25 16:10

Akshay Pratap Singh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!