How can I add an item in a list from a JSON file in Python?
Question:
Is there any way to append a JSON file list?
Here is my JSON file content:
{"language": "['English', 'French']", "bank": 50}
I would like to add the string "Spanish" to the language list.
How can I do it?
import json
with open("example.json", "r") as jsonFile:
data = json.load(jsonFile)
add list(data["language"]['Spanish'])
with open("example.json", "w") as jsonFile:
json.dump(data, jsonFile)
Answers:
In order to add to a Python list you should use the append() method.
Example:
import ast
ast.literal_eval(data["language"]).append("Spanish")
import json
import ast
with open("example.json", "r") as jsonFile:
data = json.load(jsonFile)
#data={"language": "['English', 'French']", "bank": 50}
#take a variable e
e=ast.literal_eval(data['language'])
e.append('Spanish')
data['language']=e
print(data)
#{'language': ['English', 'French', 'Spanish'], 'bank': 50}
{"language": "['English', 'French']", "bank": 50}
Here the "language" keys hold a string rather than a list because of the "
before [
and "
after ]
. To solve this, change the file to this:
{"language": ["English", "French"], "bank": 50}
Then use this code to append "Spanish" or any language from now on:
import json
with open("temp.json", "r") as f:
data = json.load(f)
data["language"].append("Spanish")
with open("temp.json", "w") as f:
json.dump(data, f)
Is there any way to append a JSON file list?
Here is my JSON file content:
{"language": "['English', 'French']", "bank": 50}
I would like to add the string "Spanish" to the language list.
How can I do it?
import json
with open("example.json", "r") as jsonFile:
data = json.load(jsonFile)
add list(data["language"]['Spanish'])
with open("example.json", "w") as jsonFile:
json.dump(data, jsonFile)
In order to add to a Python list you should use the append() method.
Example:
import ast
ast.literal_eval(data["language"]).append("Spanish")
import json
import ast
with open("example.json", "r") as jsonFile:
data = json.load(jsonFile)
#data={"language": "['English', 'French']", "bank": 50}
#take a variable e
e=ast.literal_eval(data['language'])
e.append('Spanish')
data['language']=e
print(data)
#{'language': ['English', 'French', 'Spanish'], 'bank': 50}
{"language": "['English', 'French']", "bank": 50}
Here the "language" keys hold a string rather than a list because of the "
before [
and "
after ]
. To solve this, change the file to this:
{"language": ["English", "French"], "bank": 50}
Then use this code to append "Spanish" or any language from now on:
import json
with open("temp.json", "r") as f:
data = json.load(f)
data["language"].append("Spanish")
with open("temp.json", "w") as f:
json.dump(data, f)