如何在python中将元素添加到空JSON?

问题描述:

我创建了一个空字符串&通过json.dump将其转换为JSON.一旦我要添加元素,它就会失败&显示

I created an empty string & convert it into a JSON by json.dump. Once I want to add element, it fails & show

AttributeError:'str'对象没有属性'append'

AttributeError: 'str' object has no attribute 'append'

我同时尝试了json.insert& json.append,但它们都不起作用.

I tried both json.insert & json.append but neither of them works.

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

It seems that it's data type problem. As Python can't declare data type as Java & C can, how can I avoid the problem?

import json

data = {}
json_data = json.dumps(data)
json_data.append(["A"]["1"])
print (json_data)

JSON是数据的字符串表示形式,例如列表和字典.您无需附加到JSON,而是附加到原始数据,然后将其转储.

JSON is a string representation of data, such as lists and dictionaries. You don't append to the JSON, you append to the original data and then dump it.

此外,您不将append()与字典一起使用,而是将其与列表一起使用.

Also, you don't use append() with dictionaries, it's used with lists.

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)