string is a JSON object or JSON array in Python?
<p>I am reading JSON file line by line. Few lines contain JSON objects while other contains JSON array. I am using <code>json.loads(line)</code> function to get JSON from each line. </p>

<pre><code>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
</code></pre>

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

<p>I will be thankful to you if anyone can help me.</p>

<p>The problem with your code - if  line does not contain <em>full</em> JSON object - it seldom does - it will nearly always fail.</p>

<p>Unlike in Java, in Python JSON is naturally represented by hierarchical mixture of list and dictionary elements. So, if you are looking for list elements in your JSON, you may use recursive search.</p>

<p>If you want to check if your file is valid JSON - the code below is simpler and shorter test</p>

<pre><code>try:
    with open(file_name) as f:
        json_obj = json.load(f)
    except:
        print "Not valid JSON"
</code></pre>

<p><strong>EDIT</strong>
Is it JSON file or JSON schema?</p>

<p>In the latter, you may just check if your object is list</p>

<pre><code>obj = json.loads(line)
isintance(obj, list)
</code></pre>

<p>As I have already stated, there's no such thing as "JSON object" in Python</p>

<p>PS If you read file line by line, and each line is JSON object - it's not a JSON file, it's a file where each string contains JSON. Otherwise, your test will fail on the first line already, which will be just </p>

<pre><code>{
</code></pre>

python json python-3.x