JSON for python

本文介绍了如何使用Python标准库操作JSON数据,包括编码和解码JSON数据的基本方法,并提供了简单的示例代码。

了解 json

JSON介绍
JSON官方说明
Python操作json的标准api库

练习 json

#!/usr/bin/env python
#coding:utf-8
"""
FuncName: json.py
Desc: study json for python 2.7
Date: 2016-09-06 10:30
Author: johnny
"""

import json

data = {
    'name' : 'Johnny',
    'home' : 'http://blog.youkuaiyun.com/z_johnny',
    'date' : 20160906
}

json_str = json.dumps(data)         # 字符串编码JSON数据,<type 'str'>
print type(json_str)
print repr(data),type(repr(data))   # 原始输出,repr(data),<type 'str'>

python_dict = json.loads(json_str)  # 字符串解码JSON数据,<type 'dict'>
print type(python_dict)

with open('jsonfile.json', 'w') as f:   # 文件编码JSON数据,写JSON数据
    json.dump(data, f)

with open('jsonfile.json', 'r') as f:   # 文件解码JSON数据,读JSON数据,<type 'dict'>
    data_dict = json.load(f)
    print type(data_dict)

#带参数,example:
ex = json.dumps(data,sort_keys=True,indent=4)   # sort_keys 排序,indent 缩进
print ex
"""
{
    "date": 20160906,
    "home": "http://blog.youkuaiyun.com/z_johnny",
    "name": "Johnny"
}
"""

python原始类型向json类型的转化表:
这里写图片描述

json类型到python类型转化表:
这里写图片描述

### 如何在Python中处理JSON Lines (`.jl`) 文件 JSON Lines是一种轻量级的数据交换格式,每行都是一个独立的有效 JSON 对象。为了读取和写入这种类型的文件,在 Python 中可以利用内置库 `json` 来解析每一行作为单独的对象。 #### 读取 `.jl` 文件中的数据 要从 JSON Lines 文件中加载数据,可以通过逐行打开并解码文件来实现: ```python import json def read_json_lines(file_path): data = [] with open(file_path, mode='r', encoding='utf-8') as file: for line in file: item = json.loads(line.strip()) data.append(item) return data ``` 此函数会遍历给定路径下的每一个条目,并将其转换成 Python 字典对象后存入列表返回[^1]。 #### 将数据保存到 `.jl` 文件 如果想要把一些结构化的信息存储为 JSON Lines 格式的文件,则可按照如下方式操作: ```python def write_json_lines(data, file_path): with open(file_path, mode='w', encoding='utf-8') as file: for entry in data: file.write(json.dumps(entry) + '\n') ``` 这里假设输入参数 `data` 是由字典组成的迭代器或序列;对于其中每个元素都会被转储成字符串形式追加至目标文件末尾。 需要注意的是,在实际应用过程中可能会遇到 I/O 错误的情况,比如尝试访问不存在的文件时就会抛出异常。因此建议总是使用 try-except 结构来进行错误捕获和适当处理[^2]: ```python try: items = read_json_lines('example.jl') except FileNotFoundError as e: print(f"Error occurred while opening the file: {e}") else: # Process items... finally: print("Operation completed.") ``` 通过这种方式可以在发生问题时不致于使程序崩溃,而是能够优雅地给出提示信息或者采取其他补救措施。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值