json是一种数据格式,其实就是python字典(有些微的区别,自行百度),有时我们得到的是字符串格式,需要json.load来转化一下
一般我们从网页里得到,从文件里得到,读进来是字符串格式
我进行了几个测试,然后就知道它是怎么用的了
#coding ='utf-8'
import urllib2
import json
import requests
import sys
reload(sys)
# sys_type = sys.getfilesystemencoding()
# sys.setdefaultencoding('utf-8')
# sys.setdefaultencoding(sys_type)
def test1():
print 'test1: from Internet '
html = requests.get('http://api.douban.com/v2/book/isbn/9787218087351')
print type(html.text)
hjson = json.loads(html.text)
print hjson['msg']
def test2():
print 'test12: from string '
data_str = '{"fields":["name","menu_items","location","categories","description"],"menu_item_queries":[{"price":{"$ge":6},"name":"beer"}],"venue_queries":[{"location":{"locality":"San Francisco"}}],"api_key":"YOUR_API_KEY"}'
data = json.loads(data_str)
print data['api_key']
print data['venue_queries'][0]['location']['locality']
def test3():
print 'test3: from line-feed string '
data_str2 = '{"fields":["name","menu_items","location","categories","description"],\
"menu_item_queries":[{"price":{"$ge":6},"name":"beer"}],\
"venue_queries":[{"location":{"locality":"San Francisco"}}],"api_key":"YOUR_API_KEY"}'
data2 = json.loads(data_str2)
print data2['api_key']
print data2['venue_queries'][0]['location']['locality']
def test4():
print 'the str is from Internet (same as test1)'
from_url_str = '{"msg":"invalid_request_scheme: http","code":100,"request":"GET \/v2\/book\/isbn\/9787218087351"}'
data = json.loads(from_url_str)
print data['msg']
def test5():
print 'test5: from dict '
data_dict = {"fields":["name","menu_items","location","categories","description"],\
"menu_item_queries":[{"price":{"$ge":6},"name":"beer"}],\
"venue_queries":[{"location":{"locality":"San Francisco"}}],"api_key":"YOUR_API_KEY"}
print data_dict['api_key']
print data_dict['venue_queries'][0]['location']['locality']
test1()
test2()
test3()
test4()
test5()
print 'ok'