Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to read and write JSON files by Python

2025-04-02 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)05/31 Report--

本篇内容介绍了"Python怎么读写JSON文件"的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

JSONJSON 起源

JSON 全称 JavaScript Object Notation 。是处理对象文字语法的 JavaScript 编程语言的一个子集。JSON 早已成为与语言无关的语言,并作为自己的标准存在。

JSON 样例{ "data":[ { "id": "1", "name": "A同学", "state": "1", "createTime": "2020-01-21" }, { "id": "2", "name": "B同学", "state": "1", "createTime": "2020-01-21" }, { "id": "3", "name": "C同学", "state": "0", "createTime": "2020-01-21" } ]}Python 原生支持 JSON

Python 带有一个内置包 json,用于对 JSON 数据进行编码和解码。

引用方式。

import json

JSON 编码的过程通常称为序列化。该术语是指将数据转换为一系列字节通过网络存储或传输。反序列化是解码以 JSON 标准存储或交付的数据的交互过程。

序列化 JSON

直观的转换将简单的 Python 对象转换为 JSON。

PythonJSONdictobjectlist,tuplearraystrstringint, long,floatnumberTruetrueFalsefalseNonenull简单的序列化示例

创建一个简单的数据。

data = { "data":[ { "id": "1", "name": "A同学", "state": "1", "createTime": "2020-01-21" }, { "id": "2", "name": "B同学", "state": "1", "createTime": "2020-01-21" }, { "id": "3", "name": "C同学", "state": "0", "createTime": "2020-01-21" } ]}

数据直接以文本方式保存。

with open("data_file.json", "w") as f: json.dump(data, f)

数据直接以字符串方式使用。

json_str = json.dumps(data)JSON 反序列化

在 json 库中使用 load() 和 oads() 用于将 JSON 编码数据转换为 Python 对象。

JSONPythonobjectdictarrayliststringstrnumber(整数)intnumber(浮点数)floattrueTruefalseFalsenullNone简单的反序列化示例

读取写入json文件的数据。

with open("data_file.json", "r") as read_file: data = json.load(read_file)

字符串数据。

json_string = """{ "data":[ { "id": "1", "name": "A同学", "state": "1", "createTime": "2020-01-21" }, { "id": "2", "name": "B同学", "state": "1", "createTime": "2020-01-21" }, { "id": "3", "name": "C同学", "state": "0", "createTime": "2020-01-21" } ]}"""data = json.loads(json_string)应用案例

通过互联网的数据抓取解析文本信息。

# 秦皇岛煤炭网微博import requestsfrom bs4 import BeautifulSoupimport datetimeurl = "http://news.cqcoal.com/manage/newsaction.do?method:webListPageNewsArchivesByTypeid"post_param = {'pageNum':'1','pageSize':'20','jsonStr':'{"typeid":"238"}'}return_data = requests.post(url,data =post_param)return_data = return_data.content.decode("utf-8")import jsonfor i in json.loads(return_data)["rows"]: title = i["title"] url = "http://news.cqcoal.com/blank/nc.jsp?mid="+str(i["id"]) timeStamp=int(i["pubdate"]) dateArray = datetime.datetime.utcfromtimestamp(timeStamp) date = dateArray.strftime("%Y-%m-%d") print(title,url,date)

编码和解码

自定义数据。

import json# 基础的数字字典py_object = {"c": 0, "b": 0, "a": 0}# JSON 编码json_string = json.dumps(py_object)print(json_string)print(type(json_string)){"c": 0, "b": 0, "a": 0}# JSON 解码py_obj = json.loads(json_string)print(py_obj)print(type(py_obj)){'c': 0, 'b': 0, 'a': 0}

如果遇到 TypeError: Object of type SampleClass is not JSON serializable 的错误就需要自定义编码和解码了。

import jsonclass Student: def __init__(self, name, roll_no, address): self.name = name self.roll_no = roll_no self.address = address def to_json(self): ''' 将此类的实例转换为 json ''' return json.dumps(self, indent = 4, default=lambda o: o.__dict__)class Address: def __init__(self, city, street, pin): self.city = city self.street = street self.pin = pin address = Address("Bulandshahr", "Adarsh Nagar", "203001")student = Student("Raju", 53, address)# 编码student_json = student.to_json()print(student_json)print(type(student_json)){ "name": "Raju", "roll_no": 53, "address": { "city": "Bulandshahr", "street": "Adarsh Nagar", "pin": "203001" }}# 解码student = json.loads(student_json)print(student)print(type(student)){'name': 'Raju', 'roll_no': 53, 'address': {'city': 'Bulandshahr', 'street': 'Adarsh Nagar', 'pin': '203001'}}"Python怎么读写JSON文件"的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注网站,小编将为大家输出更多高质量的实用文章!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report