在文本文件中编写JSON对象数组

时间:2019-01-24 13:39:50

标签: python json

我有一个空文件data.json,我想用一个json数组填充它。

我写了这个Python脚本:

import json

myArray = []

first = {}
second = {}
third = {}

first["id"] = 1
first["name"] = "Foo"
second["id"] = 2
second["name"] = "John" 
third["id"] = 2
third["name"] = "Doe" 

myArray.append(first)
myArray.append(second)
myArray.append(third)

with open('data.json', 'w') as my_file:
    strinfgifyied_json_array = # A function that converts myArray to a stringifyed JSON array
    my_file.write(strinfgifyied_json_array)
my_file.close()

我正在寻找一个将JSON对象数组转换为文本以编写它们的函数,如下所示:

data.json的内容:

[{"id": 1, "name": "Foo"},{"id": 2, "name": "John"},{"id": 3, name: "Doe"}]

1 个答案:

答案 0 :(得分:3)

我在代码中使用了类似的解决方案,使用了字典!看到您想要的内容,我认为它会适合您的问题。您真的只需要更改两个小事情,即如何定义字典以及如何在.json中写入数据(使用json.dump方法)

就是这样

import json

myArray = []

first = dict()
second = dict()
third = dict()

first["id"] = 1
first["name"] = "Foo"
second["id"] = 2
second["name"] = "John" 
third["id"] = 2
third["name"] = "Doe" 

myArray.append(first)
myArray.append(second)
myArray.append(third)

with open('data.json', 'w') as my_file:
    json.dump(myArray, my_file)

输出是这样的

[{"id": 1, "name": "Foo"}, {"id": 2, "name": "John"}, {"id": 2, "name": "Doe"}]

请尝试让我知道