Python之json类型数据转换

Python之json类型数据转换

json四种方法

json.loads json.dumps

 json.load  json.dump

注:s的就是来处理字符串的,没有带s的就是用来处理文件的

实例:

#!/usr/bin/env python

# -*- coding:utf8 -*-

# @Time     : 2017/11/13 14:07

# @Author   : hantong

# @File     : json1.py

# 实例1:
import json
a = dict(name='hanson',age=31,massage='You are so cool')
print(a)
print(type(a))
#可以看到a的类型是字典
b = json.dumps(a)
print(b)
print(type(b))
#把a转换为b后,b的格式变为了str
c = json.loads(b)
print(c)
print(type(c))
#再把b转换为c后,c的类型重新变为字典了
print(c['name'])
#打印c中的name


# 2.文件和json之间的转换
# load 是从文件中搞出来json数据,load是把文件转换为json数据
# dump 就是把json数据写入到文件中
#实例:把json数据写入到文件中
jsondata = ''''{'a':1,'b':2,'c':3}'''
with open('a.txt','w') as f:
    json.dump(jsondata,f)
#jsondata中的数据被写入到文件a.txt中
print('###########################')
with open('a.txt','r') as fr:
    m = json.load(fr)
#把a.txt中的内容转换为json格式数据
    print(m)
    print(type(m))
#可以看到m类型是'unicode'

执行结果:

{'age': 31, 'name': 'hanson', 'massage': 'You are so cool'}
<type 'dict'>
{"age": 31, "name": "hanson", "massage": "You are so cool"}
<type 'str'>
{u'age': 31, u'name': u'hanson', u'massage': u'You are so cool'}
<type 'dict'>
hanson
###########################
'{'a':1,'b':2,'c':3}
<type 'unicode'>


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值