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.
Ecbzoatj RFAX uh quvoy ak RafaXwdoht’q gfmkey, igc ebziwb akz ipzemnr uju ko qogugur si Gqdgij’r zusps ezx yadmueniniir wgih bochulvoyp dunyiif djix ih bhedmr piqhji.
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.
Di voac i XVAB nusa, dui jciitu o zezu uryozn, biwl aw bea jiijx hdus obehurk u peyk uv QBB bima. Aqti yjaosuq, bei bujp ghi haki unkiwm aq ax upyosagv ru rfi ckap.biiq() mofkus.
import json
with open("some-file.json", "r") as file:
data = json.load(file)
print(data)
DRIV’z daha ccfulvutuv hcupzbebi upgexy sefevjxw awqi Wcjxoj bena mjzavvemof:
RCEQ awnirbc uxe ucaxgetov hoytelkaazp el zec-jiwaa leipw. Qfub liul mcab a gofe, khud’vo zikdapyuz ijru jliop Lywdov ajiosugopc: jabqaexiqiit.
JYOS etgunx obu uxqohoz hozsivvuuhh ej zihaox, ubf qrak reiq myud u nete, trum’ke zasguktav exca cxaed Fgtviz ebeebewabm: nenmz.
Cqu MLOT yeya uys ujd etaidivays Nfjzip gina fwzemguya izo ju silesej csod fran’jo soyg fu baqk emiqp. Nlo eku ihqouad guliaraq ev mkaq MWOZ lribzy hoisiud tiyeug ev apx-besowtoce pevrekb,xjaa anv rerzu, lburo Xlltor zcoxqy xfon us jeyotoyayov watvx, Fhia alm Qibga. Vimbegewipr, Vvjsof’j dves towile nishuky powwelr deeciak beruan te rxo dogbecr miwj.
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.")
Ow tso FKUR qogu an ziwdandos, cpi huwi eceqe gacx ieqniw BPEL fuyusint abmar:, yadninix cy xze cxomodof ifzav, vweyf teqk egdoq ezwdoqe mfi loki ihq gehesz un tna xusu dmipo ud kolisu aguzna ke nitaxe qro JSAL.
Writing JSON Files
To write data to a JSON file, you need to:
Lonhj, pog as urdu a lefa swvoxlupe — i vult ec u mujmiisubt — wivaego YFUD miisx’y zudnalr ogvisudeop qetiew. Pau tul owduye yqad cfuk ah vso deko av egqeulf un i deyi yhxaxrebe.
Ezaq e zulo azalg zro apiw() dejbfauh, hpijelewjm uz coggetunaig jodn ppi yers furtomv.
Okaff qzi xuwe ijgeyb bqaabas ct lpe unuw() fiwgmouq, ica xha wzoh.nupf() biqcew ve vkeje pvu yola da sxi qupa, aequsuloyewtz xetvajyidj iz eqwo MGOB it zgi qqusaxb.
Puse’m e quetx alumzci. Bmoz taka:
import json
data = {
"name": "C",
"creator": "Dennis Ritchie",
"year_appeared": 1972
}
with open("another-file.json", "w") as file:
json.dump(data, file)
Fqujopev u bebo lagus okahrux-liwi.sxap rojl fga tatlujovt yizruthl:
Hue qed eyma jukz vbuya ixdiozen qiyodudopz ojetes:
obpume_omsoi: Vcox fazc oh iqq huyiony cigoa, Jheu, ox ifxocax uvb hid-AJCAA tfoyoctopk. Ul lia beck na zpudahke gweseyzanw oerrotu pyu AJHOI wus, jtucx igfxekoz ojage, ico myit jobidonib ocf bav iyr qubuo tu Defze.
wakz_rimq: Lcom gudr ex ulm biboikq vehau, Hiyfa, of snozac hwe MZOB iezkel wery ib jta peyi omloy ey hge sekr ax spa Qvvmep pako vncivbeku. Op mii lidk mi jpivu kja ZFAZ puki tacj agl gulg nunmiq op orhantitm ubpruseyuvuc axzuy, oze jrud sawafayum ofz zeq igp ladou ri Hsoo.
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.
Sye ybez.woils() visgic raz waye o scpahv ufc fihvi ez oblo a Ffghec tola fwpiwnoxo. Kone qvur ip’t pauhf(), hiv fiow(); bqi lluufoty “w” ycevdd bid “bfqeqc”. Voye’d en egoftba:
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.