- 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.
推薦閱讀
- Ansible Configuration Management
- 軟件架構設計
- Go Machine Learning Projects
- Blockchain Quick Start Guide
- Apache Superset Quick Start Guide
- Mastering ServiceNow Scripting
- 中國戰(zhàn)略性新興產(chǎn)業(yè)研究與發(fā)展·智能制造裝備
- Microsoft System Center Confi guration Manager
- RedHat Linux用戶基礎
- 青少年VEX IQ機器人實訓課程(初級)
- 常用傳感器技術及應用(第2版)
- 網(wǎng)絡信息安全項目教程
- Learning Couchbase
- Microsoft Office 365:Exchange Online Implementation and Migration(Second Edition)
- 這樣用Word!