+-
如何在python中向空JSON添加元素?
我创建了一个空字符串&通过json.dump将其转换为 JSON.一旦我想添加元素,它就会失败&节目

AttributeError: ‘str’ object has no attribute ‘append’

我试过了json.insert和amp; json.append但它们都不起作用.

看来这是数据类型问题.由于Python无法将数据类型声明为Java& C可以,我该如何避免这个问题?

import json

data = {}
json_data = json.dumps(data)
json_data.append(["A"]["1"])
print (json_data)
最佳答案
JSON是数据的字符串表示形式,例如列表和字典.您没有附加到JSON,您附加到原始数据然后转储它.

此外,您不使用带字典的append(),它与列表一起使用.

data = {} # This is a dictionary
data["a"] = "1"; # Add an item to the dictionary
json_data = json.dumps(data) # Convert the dictionary to a JSON string
print(json_data)
点击查看更多相关文章

转载注明原文:如何在python中向空JSON添加元素? - 乐贴网