网络编程
位置:首页>> 网络编程>> Python编程>> python 包实现JSON 轻量数据操作

python 包实现JSON 轻量数据操作

作者:autofelix  发布时间:2022-11-13 05:40:32 

标签:python,JSON,轻量,数据

一、将对象转为json字符串

  • json.dumps:将 Python 对象编码成 JSON 字符串

  • json.loads:将已编码的 JSON 字符串解码为 Python 对象

import json

data = [
{ 'name' : 'autofelix', 'age' : 27},
{ 'name' : '飞兔', 'age' : 26}
]

result = json.dumps(data, ensure_ascii=False)
print(result)

二、格式化输出

import json

data = [
{ 'name' : 'autofelix', 'age' : 27},
{ 'name' : '飞兔', 'age' : 26}
]

# 格式化输出
result = json.dumps(data, sort_keys=True, indent=4, separators=(',', ': '))
print(result)

三、将json字符串转为对象

import json

data = "[{ 'name' : 'autofelix', 'age' : 27}, { 'name' : '飞兔', 'age' : 26}]"

result = json.loads(data)
print(result)

四、安装demjson

  • 是 python 的第三方模块库,可用于编码和解码 JSON 数据

  • 包含了 JSONLint 的格式化及校验功能

pip install demjson

五、将对象转为json字符串

  • encode:将 Python 对象编码成 JSON 字符串

  • decode:将已编码的 JSON 字符串解码为 Python 对象

import demjson

data = [
{ 'name' : 'autofelix', 'age' : 27},
{ 'name' : '飞兔', 'age' : 26}
]

result = demjson.encode(data)
print(result)

六、将json字符串转为对象

import demjson

data = "[{ 'name' : 'autofelix', 'age' : 27}, { 'name' : '飞兔', 'age' : 26}]"

result = demjson.decode(data)
print(result)

来源:https://blog.51cto.com/autofelix/5212309

0
投稿

猜你喜欢

手机版 网络编程 asp之家 www.aspxhome.com