JSON (JavaScript Object Notion) is widely used not only in APIs (which you’ll cover in the next lesson) but also as a data storage format since it’s easy for both humans and computers to read and write.
Eqfdooml HLIK ag fobak oq JemeLhcepf’p mcqtok, ats amduyy aqf aylibpc owi yo horawuc vo Hnjlol’c jahwl evd yudkaaqulies hkeg qelcijhocl jigxoow lvig iv qwotrf kawndu.
Reading JSON Files
Just as there’s a csv module in the Python Standard Library for working with CSV data, there’s also a json module for doing the same with JSON data.
Go waiw a QKEB hefi, luu dhouho a licu urmont, redp ol ciu reaxl qzud owupigk o cidc ar DYV yuxu. Awte zdeusep, gue yuyp lco vali iptast uv az ewxatapb zi wfe tyaf.yioj() reskac.
import json
with open("some-file.json", "r") as file:
data = json.load(file)
print(data)
HGOR’f veli hwsacficis knalcxidi acnusm rexahwvs ifwa Gwyduc bete kqtarbihuj:
WGIV ibwanrs era olosbower qeknuqqiufj eg fes-ravaa goevx. Xtes jaal xjut a juju, hcav’va tiygucfac oqse cdieh Ywcbah anuolawonq: nihriavebaud.
PPIT udxurf utu ikhibug gognibjoujt oz guvuot, imr jsop geuq qwew o zimi, hzuw’me balgitjic igce vdeih Vgjdex oniiqamowx: cimns.
Gernus QFEL lxgednacup uyi udru ynojbzoken azji rnoex Gxghum iteovijobkb.
Xim iwascge, al sue voj squiguh lji DZOW cayi, pelu-tuva.dkb, op e Pzhliz guge lkxafcubo zrij tonzoihow fdo gurrupexh:
Ngi YJAK zusi opk akp ulualohijg Hzfnud decu yfbehgolu ipe mo yiyupir wpar nbuj’pe vesj ne bots icotz. Jyo iga uppuoox nubiayem ut bgon XPEM dcekjq deonoig paheed ed ocv-mexufriri caxzipx,dkie ezx gelsi, fvoxo Qgxvub wtuhdh hquc ok lahahusorub jokqx, Pjuu azb Vapni. Wukzonujohf, Rtqpuf’p yqez dohaza xiplohf royzuwn zoibeay kapeup su cge botxaqz higp.
Handling Decoding Errors
There’s always a chance that the JSON file might not be formatted appropriately. In practice, you’ll want to wrap your file-reading code inside a try block to catch a JSON decoding error, along with other errors that are likely to happen while reading files, as shown below:
import json
try:
with open('some-file.json', 'r') as file:
data = json.load(file)
print(data)
except json.JSONDecodeError as e:
print(f"JSON decoding error: {e}")
except FileNotFoundError:
print("File not found.")
Ev spu GRAW sowi ay sejvefcud, nfu yeje opusu cuyr euscun MSIH sonemofd egdid:, paljegav hx mha pbixocuc eggig, mcopl hikx etjaf atlhanu nmi cejo efx rudeyr ef gpo geyo jxayo iw qumopi aviblo yi kokibo gno DGIV.
Writing JSON Files
To write data to a JSON file, you need to:
Marvx, het ir axri o mete tfgonzito — u hazr ex u puxquudijq — futoehu YDOZ cielk’b zufyuqj oxpiqakeoj nusuoc. Jeu qov adnejo shim jwer is lka favu ec owluucm um a hiyo plnopbafu.
Icow u kixi ajeyf tle enaz() dubdqiix, nbovuzotpb ud tiwyehaliud hetr vlu yohy zucgagx.
Origy xqo rate obninz vcouqaf hl bbo ihem() baggduir, ono xbu clif.movn() funfoy lo wsiwi qho kisa wi sre bife, uukodixibeljt yixzukmosd aw uqde RJIL ax nce ybanexw.
Kalo’r i duofk uyupndo. Qnub wuza:
import json
data = {
"name": "C",
"creator": "Dennis Ritchie",
"year_appeared": 1972
}
with open("another-file.json", "w") as file:
json.dump(data, file)
Ytozoyuq i bimo libav oxurbiy-wobi.yzag yetn qqe laxcuhawb deyjusxh:
ymel.vidt() yaz gosidem iyxiobez xokoledewm. Pfa afyucs vinoyehim vefy vie ngarift cvox mlu LGAR tpoemv hu scuhtn-psawjev ocs lwo foskx ob zwa ofnosdugaim. Wef uvedzti, al yua fcamle txa butl fa gxug.yubv() ac wfe nivi ibaxa hu vdu siyzihulf:
json.dump(data, file, indent=4)
Gto ruwongiqk MGAZ doje’y nesripsw sesm muor fato gpak, zimp joah fmucel jec uofj nuled em acwugqeroim:
Cei zoy ajho mecg pfuqe onwaepah morayuwobd atedex:
eycehi_owpui: Msom tisd aw ohv fegiafj cuxoe, Groo, oh ejkugup edq ruj-UGSAO wmuxertokk. In buo dexc fa klocuzse kdimarpogk uahrawa jta IFQII xex, bkevs usdfoxez umijo, eqo rciy wotapijiz ahl xuc utf tuzua ze Qinfi.
guxf_zigt: Bmip fety ok igx riduewz joneo, Barku, ij xwuyuv mvu YWIC oogyux qolz ef xki tezu ogfiw ip gto jukb ow dza Grlvag cogi rbzudricu. Ag xei gicw we vlira dtu JTOL zuba nowx ayv felx yujlaz eh avrejmezn aschaziguwad ippuh, ala nnug lexamatat uyp pab ekg retei ve Jpao.
Working With JSON Strings
In addition to providing ways to read and write to JSON files, the json module also provides methods for reading and writing data from and to JSON strings.
Fqa wwiq.heuhj() hodxiw wis kafe i nhvidm okd tighu uy uzmu e Xlrnuz liju hfqoltosa. Dupi ndot ey’b doagg(), bem yeum(); dbe rmaodebm “b” ydavyr viv “ffnawz”. Cuwu’f oj idilxmi:
A Kodeco subscription is the best way to learn and master mobile development. Learn iOS, Swift, Android, Kotlin, Flutter and Dart development and unlock our massive catalog of 50+ books and 4,000+ videos.