Python 中的 string 是 JSON 对象还是 JSON 数组?

Aya*_*rar 4 python json python-3.x

我正在逐行读取 JSON 文件。少数行包含 JSON 对象,而其他行包含 JSON 数组。我正在使用json.loads(line)函数从每一行获取 JSON。

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
Run Code Online (Sandbox Code Playgroud)

有什么方法可以找出我正在读取的对象是 JSON 对象还是 JSON 数组?我想将所有结果保存在 json_array 中。

如果有人能帮助我,我将非常感谢你。

Aks*_*ngh 7

在Python中,JSON对象被转换为数据类型dict,JSON列表被转换为list数据类型。

因此,如果您想检查应该是有效JSON、 isJSON Object或的行内容JSON Array,那么此代码将帮助您:-

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)
Run Code Online (Sandbox Code Playgroud)