英文:
How can I add an item in a list from a JSON file in Python?
问题
import json
with open("example.json", "r") as jsonFile:
data = json.load(jsonFile)
data["language"].append('Spanish') # Append 'Spanish' to the 'language' list
with open("example.json", "w") as jsonFile:
json.dump(data, jsonFile)
英文:
I'm working with a JSON file and I was wondering if there's a way to append a string to a list within the file. Here's an example of the JSON file I'm working with:
{"language": "['English', 'French']", "bank": 50}
I want to add the string "Spanish" to the "language" list. How can I do this?
Here's the code I've written so far, but I'm not sure how to modify it to achieve what I want:
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)
How can I modify this code to achieve my goal?
答案1
得分: 2
{ "language": ["English", "French"], "bank": 50 }
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)
英文:
> {"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)
答案2
得分: 1
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}
英文:
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}
答案3
得分: 0
要向Python列表中添加元素,你应该使用append()
方法。
示例:
import ast
ast.literal_eval(data["language"]).append("Spanish")
英文:
In order to add to a Python list you should use the append() method.
Example:
import ast
ast.literal_eval(data["language"]).append("Spanish")
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论