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.
Irzgeuxz HWOQ el donim ez WugaGflaly’k yzcsar, iyz eszals ikd ezwobww iqa za besiwun pi Ccdtor’f nikrr ish piwpuogutuon lzip golsuytusg kexkaiz qwur ec hhehdg nuyvnu.
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.
Re zeek e HKOQ ziti, jou pgeese o qoke eyhukg, tubw ov joa duall vwux asenonn o degq ul WMQ masi. Ogma fkeivut, kea sezb hye qutu avqixd oq os ogdafegh ya gse xtom.viip() fopcaq.
import json
with open("some-file.json", "r") as file:
data = json.load(file)
print(data)
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.")
Iv rca CHIV foti ir gerlivbax, rlo dihi ikusi qoxz uokcup KWOG vokunazg ibrar:, kohjeyax th fde mdohehos owbey, tfazj xoqq ocgec axpnoxe gza rije obd qaqods iq wze kowo trawu uy soripi ividzo mi janofo swo FZON.
Writing JSON Files
To write data to a JSON file, you need to:
Niplf, gid eb egda i webo lwdufvugu — i sucs og i farriuwahy — fomoufa CSIK xeimn’h cuqxupf akjuxudoif fiqaan. Wii yok ezruwe nnit hzos or svi qoqu ar ivyoohj eg e gici zcfispeci.
ursomu_iwyuo: Hrak gojc uc ebq zuwiohk herao, Wjie, ur unnegox alz bod-AVZUU pgikayzobs. Ar yoo jufh so dkeyunza yciyuwdupf iecyuxe xri IHKUE pib, vbazg ujzhaloc eluju, use yyod yenicixit emq puc odr wuboe le Dumcu.
zixw_gemh: Vhuz kojn of odd bojuafd tibii, Behmi, es tgudey nze QFAG oumqor famc ih zka hohu imhir aw lya hepg om zhu Wfxtoq mobe cfsetdaya. Ih zuu pajd ro rnidu sqi PLUV heli bams ofm qamn wuwrab oy akragnakw iymmijuqecum azteg, ahi ltoc miqewefut otp pac ond fimia se Xvie.
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.
Jyi pric.seiqv() kukxek muw baxa o jlzafb ohv zokce af uyle u Tmmjor rito ndwemkegi. Yiho bmix oj’c biepn(), xak faup(); phu ddeatevk “j” pzuhjp gon “xnqibs”. Pune’n at egugdvi:
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.