您现在的位置是:网站首页> 编程资料编程资料

python 包实现JSON 轻量数据操作_python_

2023-05-26 365人已围观

简介 python 包实现JSON 轻量数据操作_python_

一、将对象转为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)

到此这篇关于python 包中的JSON 轻量数据操作教程的文章就介绍到这了,更多相关JSON 轻量数据操作内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

-六神源码网