数据科学必备Json序列化数据进行读写方法详解

学Python数据科学,玩游戏、学日语、搞编程一条龙。

整套学习自学教程中应用的数据都是《三國志》、《真·三國無雙》系列游戏中的内容。

JSON 数据类型最常用的应用场景就是 API 或将数据保存到 .json 文档中。使用 Python 处理这些数据会变得非常简单。
在这里插入图片描述

JSON

JSON 起源

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

JSON 样例

{
    
    
	 "data":[
	  {
    
    
	    "id": "1",
	    "名前": "阿会喃",
	    "寿命": "36",
	    "分類": "武官"
	  },
	  {
    
    
	    "id": "2",
	    "名前": "韋昭",
	    "寿命": "70",
	    "分類": "文官"
	  },
	  {
    
    
	    "id": "3",
	    "名前": "伊籍",
	    "寿命": "65",
	    "分類": "文官"
	  }
	]
}

Python 原生支持 JSON

Python 带有一个内置包 json,用于对 JSON 数据进行编码和解码。
在这里插入图片描述

引用方式。

import json

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

序列化 JSON

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

Python JSON
dict object
list,tuple array
str string
int, long,float number
True true
False false
None null

简单的序列化示例

创建一个简单的数据。

扫描二维码关注公众号,回复: 14156019 查看本文章
data =   {
    
    
	 "data":[
	  {
    
    
	    "id": "1",
	    "名前": "阿会喃",
	    "寿命": "36",
	    "分類": "武官"
	  },
	  {
    
    
	    "id": "2",
	    "名前": "韋昭",
	    "寿命": "70",
	    "分類": "文官"
	  },
	  {
    
    
	    "id": "3",
	    "名前": "伊籍",
	    "寿命": "65",
	    "分類": "文官"
	  }
	]
}

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

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

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

json_str = json.dumps(data)

JSON 反序列化

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

JSON Python
object dict
array list
string str
number(整数) int
number(浮点数) float
true True
false False
null None

简单的反序列化示例

读取写入json文件的数据。

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

字符串数据。

json_string = """
{
	 "data":[
	  {
	    "id": "1",
	    "名前": "阿会喃",
	    "寿命": "36",
	    "分類": "武官"
	  },
	  {
	    "id": "2",
	    "名前": "韋昭",
	    "寿命": "70",
	    "分類": "文官"
	  },
	  {
	    "id": "3",
	    "名前": "伊籍",
	    "寿命": "65",
	    "分類": "文官"
	  }
	]
}
"""
data = json.loads(json_string)

应用案例

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

# 秦皇岛煤炭网微博
import requests
from bs4 import BeautifulSoup
import datetime
url = "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 json
for 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}
<class 'str'>


# JSON 解码
py_obj = json.loads(json_string)

print(py_obj)
print(type(py_obj))

{
    
    'c': 0, 'b': 0, 'a': 0}
<class 'dict'>

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

import json

class Person:
	def __init__(self, name, gender, ability):
		self.name = name
		self.gender = gender
		self.ability = ability

	def to_json(self):
		'''
		将此类的实例转换为 json
		'''
		return json.dumps(self, ensure_ascii=False,indent = 4, default=lambda o: o.__dict__)

class Ability:
	def __init__(self, force, intelligence , politics , commander):
		self.force= force
		self.intelligence = intelligence
		self.politics = politics
		self.commander= commander


ability = Ability("74", "26", "26" , "65")
person = Person("阿会喃", "男", ability )

# 编码
person_json = person.to_json()
print(person_json)
print(type(person_json))

{
    
    
    "name": "阿会喃",
    "gender": "男",
    "ability": {
    
    
        "force": "74",
        "intelligence": "26",
        "politics": "26",
        "commander": "65"
    }
}
<class 'str'>

# 解码
person = json.loads(person_json)
print(person )
print(type(person ))

{
    
    'name': '阿会喃', 'gender': '男', 'ability': {
    
    'force': '74', 'intelligence': '26', 'politics': '26', 'commander': '65'}}
<class 'dict'>

猜你喜欢

转载自blog.csdn.net/qq_20288327/article/details/124779091