Uyithelekisa njani iJSON kwiPython

Siyijonga njani iJSON kwiPython. Kuqala silayisha ifayile yeJSON sisebenzisa json.load () indlela. Iziphumo sisichazi magama sePython. Emva koko sinokufikelela emasimini sisebenzisa iindlela zesichazi-magama.

IJSON yifomathi yokutshintshiselana ngedatha elula.

Ukukhupha ulwazi kwifayile yeJSON okanye impendulo yeJSON, kufuneka sihlolisise idatha.




Cacisa iJSON kwiPython

Siza kusebenzisa le JSON ilandelayo kumzekelo wethu:

{ 'store':{
'book':[

{

'category':'reference',

'author':'Nigel Rees',

'title':'Sayings of the Century',

'price':8.95

},

{

'category':'fiction',

'author':'Evelyn Waugh',

'title':'Sword of Honour',

'price':12.99

}
],
'bicycle':{

'color':'red',

'price':19.95
} }, 'expensive':10 }

Inyathelo lokuqala kukulayisha ifayile yeJSON kwiPython:


import json with open('store.json') as json_file:
data = json.load(json_file) print(data)

Ifayile yeJSON ngoku igcinwe kwi- data umahluko.



Indlela yoshicilelo iya kuprinta le JSON ingasentla.

Phawula:Le ndlela ingentla iya kugcina iJSON njenge Isichazi magama . Singakujonga oku ngokuprinta uhlobo, phrinta (uhlobo (idatha)).

Isifundo seJSON -Funda ukuba uyisebenzisa kanjani iJSON ngeJavaScript



Ukukhupha idatha ekhethekileyo kwiJSON

Ngoku ekubeni sinayo iJSON yethu njengesichazi magama sePython, singalanda idatha ethile ngokuchaza intsimi, emele key kwisichazi magama.

Umzekelo, ukulanda ixabiso lebhayisekile kule JSON ingasentla, siya kusebenzisa:


print(data['store']['bicycle']['price'])

Iziphumo:

19.95

Khupha idatha kwiJSON Array

Kumzekelo weJSON ongentla, intsimi 'yencwadi' yiJSON Array.

Sinokusebenzisa isalathiso sokuphawula amanqaku xa silanda izinto ezithile.

Umzekelo, ukufumana igama lencwadi yesibini esinokuyisebenzisa:


print(data['store']['book'][1]['title'])

Iziphumo:

Sword of Honour

Ukwahlulwa ngokuxhomekeke kuJSON

Masithi sifuna ukufumana zonke iincwadi ezinamaxabiso angaphantsi okanye alingane ne-10.00.

Emva koko siya kusebenzisa:

books = data['store']['book'] for book in books:
if book['price'] <= 10.00:
print(book)

Iziphumo:


{'category': 'reference', 'author': 'Nigel Rees', 'title': 'Sayings of the Century', 'price': 8.95}

Isiphelo

Kule posi sijonge indlela yokuhluza iJSON kwiPython. Eyona nto ithathwa apha kukuba xa ifayile yeJSON ilayishiwe, igcinwa njengesichazi-magama sePython. Nje ukuba sibe nesichazi-magama, emva koko sinokusebenzisa iindlela eziqhelekileyo zesichazi-magama ukukhupha amaxabiso athile kwiJSON.