4

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)
1
  • 2
    Add it to the dictionary (not a string) before you dump it to a string (not "a JSON")? Commented Dec 21, 2018 at 9:47

1 Answer 1

4

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)
Sign up to request clarification or add additional context in comments.

3 Comments

it looks like OP is confused about what is what, i,e, data is not string, but dict and json_data is in fact string, etc. Maybe add some explanation about that if you like
I've added some explanation of the difference.
Thanks! It's works. So if I want to add new element, I need to convert the json string back to dict instead of deal with json string directly?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.