python json文件的使用

json是一種輕量級數據交換格式,經常使用於http請求中,在平常運維工做中常常能夠看到python


1.json類型和python數據的轉換json

函數轉換對應關係表:運維

Python JSON
dict object
list, tuple array
str, unicode string
int, long, float number
True true
False false
None null


1)將json數據寫入文件json.dump()ide

例子:函數

import jsonurl

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

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

json.dump(json_data,f)orm

f.close()ip


結果:目錄下生成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)

相關文章
相關標籤/搜索