In: Computer Science
Python programming problem!
Suppose that there is a json file called data from the desktop. I want to print the value with the key of "year" and "country".
Json file below:
{
"A":{
"year":11,
"grade":A,
"country":America},
"B":{
"year":18,
"grade":C,
"country":England},
"C":{
"year":19,
"grade":B,
"country":China},}
I want a code that I can only replace the name of key from year to grade and the code could be work.
import json fName = input('Enter json file name: ') lines = open(fName).readlines() lines = [l.strip() for l in lines if l.strip() != ''] content = ' '.join(lines) dataDict = json.loads(content) # You cna print below to check the dict content #print(dataDict) # now you want to print the value for key 'year' for (x, y) in dataDict.items(): print(y['year']) print(y['country']) # to change the key in dict object for (x, y) in dataDict.items(): print(y['year']) print(y['country']) # to change the key in dict object for (x, y) in dataDict.items(): # change year key to year1 y['year1'] = y['year'] del y['year'] print(dataDict)
===========================
Your json file is incorrect. That is not a valid json. The
strigns should be enclosed in quotes..
The valid json is below:
{
"A":{
"year":11,
"grade":"A",
"country":"America"},
"B":{
"year":18,
"grade":"C",
"country":"England"},
"C":{
"year":19,
"grade":"B",
"country":"China"}}
================
Please upvote, as i have given the exact answer as asked in
question. Still in case of any concerns in code, let me know in
comments. Thanks!