- Hands-On Artificial Intelligence for IoT
- Amita Kapoor
- 158字
- 2021-07-02 14:02:00
Using JSON files with the JSON module
To load and decode JSON data, use the json.load() or json.loads() functions. As an example, the following code reads the first 10 lines from the zips.json file and prints them nicely:
import os
import json
from pprint import pprint
with open(os.path.join(data_folder,data_file)) as json_file:
for line,i in zip(json_file,range(10)):
json_data = json.loads(line)
pprint(json_data)
The objects are printed as follows:
{'_id': '01001', 'city': 'AGAWAM', 'loc': [-72.622739, 42.070206], 'pop': 15338, 'state': 'MA'}
The json.loads() function takes string objects as input while the json.load() function takes file objects as input. Both functions decode the JSON object and load it in the json_data file as a Python dictionary object.
The json.dumps() function takes an object and produces a JSON string, and the json.dump() function takes an object and writes the JSON string to the file. Thus, both these function do the opposite of the json.loads() and json.load() functions.
推薦閱讀
- 大數據戰爭:人工智能時代不能不說的事
- Design for the Future
- Mastercam 2017數控加工自動編程經典實例(第4版)
- Getting Started with Clickteam Fusion
- Linux Mint System Administrator’s Beginner's Guide
- 電腦上網直通車
- 視覺檢測技術及智能計算
- CompTIA Network+ Certification Guide
- 氣動系統裝調與PLC控制
- Hands-On SAS for Data Analysis
- 筆記本電腦維修之電路分析基礎
- 算法設計與分析
- JSP通用范例開發金典
- 開放自動化系統應用與實戰:基于標準建模語言IEC 61499
- SQL Server 2019 Administrator's Guide