前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >python json文件的使用

python json文件的使用

作者头像
py3study
发布2020-01-06 22:05:14
2K0
发布2020-01-06 22:05:14
举报
文章被收录于专栏:python3python3

json是一种轻量级数据交换格式,常用于http请求中,在日常运维工作中经常可以看到

1.json类型和python数据的转换

函数转换对应关系表:

Python

JSON

dict

object

list, tuple

array

str, unicode

string

int, long, float

number

True

true

False

false

None

null

1)将json数据写入文件:json.dump()

例子:

import json

json_data = {"a":1,"b":2,"c":3,"d":4,"e":5,"f":6}

f = open("a.txt","w")

json.dump(json_data,f)

f.close()

结果:目录下生成a.txt文件,内容:

{"a": 1, "c": 3, "b": 2, "e": 5, "d": 4, "f": 6}

2)读取文件中json数据,显示为unicode类型格式:json.load()

import json

# json_data = {"a":1,"b":2,"c":3,"d":4,"e":5,"f":6}

# f = open("a.txt","w")

# json.dump(json_data,f)

# f.close()

f2 = open("a.txt","r")

dict2 = json.load(f2)

print(dict2)

结果:

{u'a': 1, u'c': 3, u'b': 2, u'e': 5, u'd': 4, u'f': 6}

3)python字典—>(转换)json字符串:json.dumps()

例子:

import json

m = {"success":"yes","message":"hello"}

json_str = json.dumps(m)

print(m)

print(type(m))

print(json_str)

print(type(json_str))

结果:

{'message': 'hello', 'success': 'yes'}

<type 'dict'>

{"message": "hello", "success": "yes"}

<type 'str'>

4)json字符串—>(解码)pyhton字典:json.loads()

例子:

import json

m = {"success":"yes","message":"hello"}

json_str = json.dumps(m)

print(json_str)

print(type(json_str))

json_dict = json.loads(json_str)

print(json_dict)

print(type(json_dict))

结果:

{"message": "hello", "success": "yes"}

<type 'str'>

{u'message': u'hello', u'success': u'yes'}

<type 'dict'>

2.爬虫举例

import json

import urllib2

from pip._vendor.requests.packages import chardet

url = 'http://'

req = urllib2.Request(url)

res = urllib2.urlopen(req)

result = res.read()

print(chardet.detect(result))

m = json.loads(result)

print(type(m))

print(m)

本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-09-19 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档