Python:将多个json对象写入文件;稍后通过json.load打开并加载

时间:2016-08-12 16:16:17

标签: python json

我从数据流构造了一个json对象,每个用户都有一个json对象。

{
    "entities": {
        "description": {
            "urls": []
        }
    },
    "utc_offset": -10800,
    "id"
    "name": "Tom",
    "hit_count": 7931,
    "private": false,
    "active_last_month": false,
    "location": "",
    "contacted": false,
    "lang": "en",
}

目标:我想构建一个json文件,其中每个json对象都成为带缩进的文件中的一行。当回读JSON文件时,可以使用open:

来读取它

例如:关注文件

[
{
    "entities": {
        "description": {
            "urls": []
        }
    },
    "utc_offset": -10800,
    "id"
    "name": "Tom",
    "hit_count": 7931,
    "private": false,
    "active_last_month": false,
    "location": "",
    "contacted": false,
    "lang": "en",
}
,
{
    "entities": {
        "description": {
            "urls": []
        }
    },
    "utc_offset": -10500,
    "id"
    "name": "Mary",
    "hit_count": 554,
    "private": false,
    "active_last_month": false,
    "location": "",
    "contacted": false,
    "lang": "en",
}
]

以上文件可以通过以下方式轻松阅读:

with open(pathToFile) as json_file:
     json_data = json.load(json_file)
     for key in json_data:
         print key["id"]

但目前我正在编写构建json文件的方式:

with open(root + filename + '.txt', 'w+') as json_file:
        # convert from Python dict-like structure to JSON format
        jsoned_data = json.dumps(data)
        json_file.write(jsoned_data)
        json_file.write('\n')

这给了我

{
   indented json data
}
{
   indented json data
}

PS:通知括号[],

不同

当您尝试读取与

相同的代码结构时
with open(pathToFile) as json_file:
     json_data = json.load(json_file)
     for key in json_data:
         print key["id"]

你最终得到错误: ValueError: Extra data: line 101 column 1 - line 1889 column 1

1 个答案:

答案 0 :(得分:-1)

我认为你应该将新的JSON数据添加到包含先前数据的列表中:

newData = {"entities": {
    "description": {
        "urls": []
    }
},
"utc_offset": -10500,
"id": 3,
"name": "Mary",
"hit_count": 554,
"private": False,
"active_last_month": False,
"location": "",
"contacted": False,
"lang": "en"
}

def readFile():
    with open('testJson', 'r') as json_file:
        json_data = json.load(json_file)
        for key in json_data:
            print key["id"]

def writeFile():
    with open('testJson', 'r') as json_file:
        oldData = json.load(json_file)
    with open('testJson', 'w+') as json_file:
        # convert from Python dict-like structure to JSON format
        data = oldData.append(newData)
        jsoned_data = json.dumps(oldData, indent=True)
        json_file.write(jsoned_data)

if __name__ == '__main__':
    readFile()
    writeFile()
    readFile()