在文本文件中写入一组 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"}]


白猪掌柜的
浏览 218回答 1
1回答
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python