Python中json数据转换问题

JSON

json简单说就是javascript中的对象和数组,所以这两种结构就是对象和数组两种结构,通过这两种结构可以表示各种复杂的结构.
Python 2.7中自带了JSON模块,直接import json就可以使用了。

import json

json 模块提供了4个功能模块:dumps、dump、loads、load 用于字符串与python数据转换

1.json.loads()
  把Json格式字符串解码转换成Python对象 从json到python的类型转化对照如下:
   ![这里写图片描述](https://img-blog.csdn.net/20170923180515348?watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQvd194X3NfaF9o/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA==/dissolve/70/gravity/SouthEast)
# 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_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编码,会导致中文无法正常显示
print json.dumps(dictStr) 
# {"city": "\u5317\u4eac", "name": "\u5927\u732b"}

# **记住:处理中文时,添加参数 ensure_ascii=False 来禁用ascii编码**
print json.dumps(dictStr, ensure_ascii=False) 
# {"city": "北京", "name": "大刘"}
3.json.dump()

将Python内置类型序列化为json对象后写入文件,实际上就是将一个类型进行序列化后转换为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'}

总结来说 load() 和loads()方法都是将字符串转化为python内置类型,dumps()和dump()方法相反,但是区别点在于load()和dump()方法都是涉及到文件的写入和写出。

在转换的过程中涉及到中文乱码的问题,一定要注意(ensure_ascii=False)


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值