I created an empty string & convert it into a JSON by json.dump. Once I want to add element, it fails & show
AttributeError: 'str' object has no attribute 'append'
I tried both json.insert & json.append but neither of them works.
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 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.
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)