【问题标题】:How to write a json file inside of a for loop?如何在 for 循环中编写 json 文件?
【发布时间】:2021-04-17 07:41:15
【问题描述】:

如何存储 for 循环的结果?如何在循环内创建 json 文件?在每次迭代的这个循环中,我打印 2 个值 print(a1,a2)。现在我想将所有这些值存储在一个 json 文件中。

【问题讨论】:

  • 请用您尝试过的代码更新您的问题。
  • 字典是 json 对象的 python 版本。尝试使用它
  • a list 是 json 数组的 python 版本。你可以试试。
  • 我可以使用打开的文件来写文件吗?
  • 是的,你可以,但我认为第一步是生成一些数据。你试过什么代码?

标签: python json file write


【解决方案1】:

你不应该在循环的里面写json文件,你应该建立一个字典或字典列表,然后用json.dump()写它

import json

# initialize the dictionary
my_dict = {}

# loop to emulate your data structure
for i in range(10):
    # assign a1 and a2
    a1 = i
    a2 = i ** 2 # just so the value is different than the key for demonstration
    # set a1 as the key and a2 as the value
    my_dict[a1] = a2

# use json.dump to write the file
with open('./square.json', 'w') as file:
    json.dump(my_dict, file, indent=4)

输出(square.json):

{
    "0": 0,
    "1": 1,
    "2": 4,
    "3": 9,
    "4": 16,
    "5": 25,
    "6": 36,
    "7": 49,
    "8": 64,
    "9": 81
}

【讨论】:

  • TypeError: 响应类型的对象不是 JSON 可序列化的
  • @elham response.json() 会给你requests.<method> 的json,你不能将任何对象传递给json.dump(),它需要是一个字典或字典列表,如果代码仍然不适合您,请使用您当前的代码更新问题。
猜你喜欢
  • 2014-08-16
  • 2010-09-08
  • 2022-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多