My JSON resource is out and I'm trying to fill in the gaps, so bear with me, as I don't quite know the terminology here. I'm working to update the worlds simplest JSON File in Python.
Current a.json
:
{"quarters": ["Q2-2019", "Q3-2019", "Q4-2019", "Q1-2020", "Q2-2020", "Q3-2020", "Q4-2020",
"Q1-2021"]}
I'm looking to append to this, with a result of
{"quarters": ["Q2-2019", "Q3-2019", "Q4-2019", "Q1-2020", "Q2-2020", "Q3-2020", "Q4-2020",
"Q1-2021", "Q2-2021"]}
I can't seem to find a way to quickly add within the quarters "tag". I've been able to create new "tags", but that's not my intent here.
Use json.load()
to parse the JSON into a dictionary. Then just append to the list in the dictionary and write it back out with json.dump
import json
with open('a.json') as f:
data = json.load(f)
data['quarters'].append('Q2-2021')
with open('a.json', 'w') as f:
json.dump(f, data)
a["quarters"].append("new_quarter")
should do it. If it isn't in JSON format already:
a = json.loads(a)
a["quarters"].append("new_quarter")
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.