官术网_书友最值得收藏!

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.

主站蜘蛛池模板: 宁远县| 淳安县| 敖汉旗| 耒阳市| 澳门| 康保县| 婺源县| 溆浦县| 西林县| 米泉市| 石河子市| 云林县| 临漳县| 南京市| 永川市| 碌曲县| 琼结县| 萨嘎县| 腾冲县| 姜堰市| 兴化市| 全南县| 永安市| 辽阳市| 枣庄市| 伊金霍洛旗| 阿城市| 望都县| 施秉县| 长兴县| 东乡族自治县| 遵义市| 行唐县| 乌兰察布市| 增城市| 海城市| 淮南市| 根河市| 奉节县| 科尔| 鄂托克前旗|