使用python解析Json字符串

您所在的位置:网站首页 python如何提取字符串中的字符 使用python解析Json字符串

使用python解析Json字符串

2023-06-07 12:32| 来源: 网络整理| 查看: 265

json简单说就是javascript中的对象和数组,所以这两种结构就是对象和数组两种结构,通过这两种结构可以表示各种复杂的结构

对象:对象在js中表示为{ }括起来的内容,数据结构为 { key:value, key:value, ... }的键值对的结构,在面向对象的语言中,key为对象的属性,value为对应的属性值,所以很容易理解,取值方法为 对象.key 获取属性值,这个属性值的类型可以是数字、字符串、数组、对象这几种。

数组:数组在js中是中括号[ ]括起来的内容,数据结构为 ["Python", "javascript", "C++", ...],取值方式和所有语言中一样,使用索引获取,字段值的类型可以是 数字、字符串、数组、对象几种

1. json.loads()

把Json格式字符串解码转换成Python对象 从json到python的类型转化对照如下:

 

 

# json_loads.py

 

import json

 

strList = '[1, 2, 3, 4]'

 

strDict = '{"city": "北京", "name": "大猫"}'

 

json.loads(strList)

# [1, 2, 3, 4]

 

json.loads(strDict) # json数据自动按Unicode存储

# {u'city': u'\u5317\u4eac', u'name': u'\u5927\u732b'}

  2. json.dumps()

实现python类型转化为json字符串,返回一个str对象 把一个Python对象编码转换成Json字符串

从python原始类型向json类型的转化对照如下:

 

 

# json_dumps.py

 

import json

import chardet

 

listStr = [1, 2, 3, 4]

tupleStr = (1, 2, 3, 4)

dictStr = {"city": "北京", "name": "大猫"}

 

json.dumps(listStr)

# '[1, 2, 3, 4]'

json.dumps(tupleStr)

# '[1, 2, 3, 4]'

 

# 注意:json.dumps() 序列化时默认使用的ascii编码

# 添加参数 ensure_ascii=False 禁用ascii编码,按utf-8编码

# chardet.detect()返回字典, 其中confidence是检测精确度

 

json.dumps(dictStr)

# '{"city": "\\u5317\\u4eac", "name": "\\u5927\\u5218"}'

 

chardet.detect(json.dumps(dictStr))

# {'confidence': 1.0, 'encoding': 'ascii'}

 

print json.dumps(dictStr, ensure_ascii=False)

# {"city": "北京", "name": "大刘"}

 

chardet.detect(json.dumps(dictStr, ensure_ascii=False))

# {'confidence': 0.99, 'encoding': 'utf-8'}

 

chardet是一个非常优秀的编码识别模块,可通过pip安装

3. json.dump()

将Python内置类型序列化为json对象后写入文件

 

# json_dump.py

 

import json

 

listStr = [{"city": "北京"}, {"name": "大刘"}]

json.dump(listStr, open("listStr.json","w"), ensure_ascii=False)

 

dictStr = {"city": "北京", "name": "大刘"}

json.dump(dictStr, open("dictStr.json","w"), ensure_ascii=False)

  4. json.load()

读取文件中json形式的字符串元素 转化成python类型

 

# json_load.py

 

import json

 

strList = json.load(open("listStr.json"))

print strList

 

# [{u'city': u'\u5317\u4eac'}, {u'name': u'\u5927\u5218'}]

 

strDict = json.load(open("dictStr.json"))

print strDict

# {u'city': u'\u5317\u4eac', u'name': u'\u5927\u5218'}

转:https://blog.csdn.net/JustFORfun233/article/details/79513723

https://blog.csdn.net/kaka735/article/details/46009731



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3