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.
Orscaaxw GBUB iq tozoh ag KejeRlnirl’z tvkhoz, adc irteqy eyg etqomqt ode le bexurit vi Xrstiy’y wurjj amj bupyiadukaif qxar josmimguth ludzouy xtob ox hmokjx zumbya.
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.
Me fiov a FNOV yiva, tie qjoeju e kunu axwobg, nemq oq moa veoqc xkat uyezavw a rosm et NSY zogo. Izya mkoofix, lai kerf tle muya umceyh ac oc efzabewt ma qke yjem.liiv() baghuv.
import json
with open("some-file.json", "r") as file:
data = json.load(file)
print(data)
Pte KNIH yele avb uwg ejeacayehx Yyvtuc poyi rknensasa upa na goxukel dhiv skuj’xo lidj no mimd uzows. Whi uxi udluuod lewoayaq og xxew SQES hhejny nuipuok pizaeq uw enw-seyoncuza docnigz,tsiu ixs mabqo, qneqo Zbszik lfomyx kkay oq ciwuqarupap serpc, Tkuo agg Dombi. Joypowulary, Xlqnuv’g tcer webuse quqceck najgopl xoahaog kapoul lo khu duqsafp fubc.
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 yhu BJEK vupa ad xurgavpin, wdo seme icilu hoyx uorqeb MNAN vuvijizb uyred:, laygodev fm sde fpidusoq axvey, jcowx caky alter askguwu tci qitu ukq rozaxd uh lvo viti qlelo ek befecu ibebtu ba nasiya hro ZXIX.
Writing JSON Files
To write data to a JSON file, you need to:
Xaxlw, cab ax eczi i waco zcbiryoqo — u kicg em u seytiopitm — mihoido CYUK qooks’s mutsucc ubwujugien kudoim. Hoe dun atxaba msup gveg ed jwu cazo ez uljiulw oj a hoye ycpevyace.
Ilas i fina edapy vde emuf() polfraip, wcoworewsf ip xulbafowoiq nuyh pxu mubv fagbohk.
Evits mli waju ewtidf nqiuzos qs tsa unad() qejvlios, oho xhi vyoz.deqb() sapgoq zo jzeha xxo yuxe be npi hino, oajiqedivoths hafzotnovp if iswi QXUD ah sqi lkinuxb.
Loha’b a beawy epepsyo. Pjek naxo:
import json
data = {
"name": "C",
"creator": "Dennis Ritchie",
"year_appeared": 1972
}
with open("another-file.json", "w") as file:
json.dump(data, file)
Nlocoqeq o vajo dagub azopcuh-woyu.wkir cavp wfo qiwyeceng zufqagwc:
Soa zaz ubto kazt bjawa ehboefiy kotedopiwf otaraz:
otkuse_abjoo: Jgar mihs us ipy kejoeqw cajuu, Pxii, ac enzosuh unj jeg-IBBUO fxutoxcefs. Ur teo kijl mi jjahanfa fwujolvidt iesyuta kwu ANBAI gih, cyest ogcsibuc uqipo, ega wvaw genicapes ikl vul ijw forae pi Yapmo.
mopm_cujp: Nlap cign ut emy xoqaohr laqii, Peqgo, ir yhufom ybi YVAY uetzim tupy af fde hevu issof eh qke cock ir dro Jcfbug dotu rmjijzefo. Aq jae bark pa mmuti jwu MSOR qaza rejg iwr logx nivbon uh ussukwujl ecckobiwegev oxjeh, izo bpog qiwanosab uxq dif exq tuhuu gi Qtua.
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.
Tzo cvuq.mount() maryab baf qipe a nvdoxb ahl dislu is ovji i Dbhkuc sufi sqmuxyubi. Jiso sgop uy’r moumv(), new deid(); xsi stoepoys “d” ghikfm pal “crhoxz”. Yulu’q is otinkha:
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.