从python中的字符串获取JSON对象
最简单的工作示例:从python中的字符串获取JSON对象,python,json,Python,Json,最简单的工作示例: import json, urllib front_url = "http://chroniclingamerica.loc.gov/search/titles/results/?city=&rows=" number_rows = "1" middle_url = "&terms=&language=&lccn=&material_type=&year1=1690&year2=2016&labor=&
import json, urllib
front_url = "http://chroniclingamerica.loc.gov/search/titles/results/?city=&rows="
number_rows = "1"
middle_url = "&terms=&language=&lccn=&material_type=&year1=1690&year2=2016&labor=&county=&state=&frequency=ðnicity=&page="
page = "1"
end_url = "&sort=relevance&format=json"
url = front_url + number_rows + middle_url + page + end_url
response = urllib.urlopen(url)
data = json.loads(response.read())
问题是,数据
对象识别JSON的顶层(totalItems
,endIndex
,startIndex
,itemsPerPage
,以及项
),然而,项
对象也应该具有应该识别的子级(随笔
,郡
,标题(正常
,lccn
)等)。如果你使用数据['items],代码只会为项
对象吐出一个混乱的字符串
我希望能够将项目
层中包含的每种不同价格的信息最终提取到一个数组或类似的东西中。我如何才能做到这一点?在您的示例JSON数据中(您应该在其中直接链接)您可以清楚地看到,项
是一个对象列表。在本例中,它只是一个带有键的对象。该键的值是一个字符串列表(在本例中,只有一个字符串)
但是,这个字符串不是JSON。它是XHTML。它当然不是由JSON.loads
解析的
我相信这个字符串就是你所说的“凌乱字符串”。项中的其他数据被json解析得很好。加载你的代码工作得很好
您只是不明白数据['items']
是一个列表
因此,要访问此列表的每个元素,必须使用从0
到len(数据['items'))的索引
advice:使用pprint
查看json文件中的clear
import json, urllib
import pprint
pp = pprint.PrettyPrinter(indent=1, width=80)
front_url = "http://chroniclingamerica.loc.gov/search/titles/results/?city=&rows="
number_rows = "1"
middle_url = "&terms=&language=&lccn=&material_type=&year1=1690&year2=2016&labor=&county=&state=&frequency=ðnicity=&page="
page = "1"
end_url = "&sort=relevance&format=json"
url = front_url + number_rows + middle_url + page + end_url
response = urllib.urlopen(url)
data = json.loads(response.read())
pp.pprint(data['items'][0]) # [0] to get the first item
print data['items'][0]['essay'] # get the essay element of the first item
print data['items'][0]['country'] # get the country element of the first item
你想做这样的事吗
for item in data['items']:
print item['county']
print item['title_normal']
print item['lccn']
因为只有一个项目,所以输出以下内容
[u'Bates']
butler weekly times and the bates county record.
sn86063289
您的代码非常好。您可以迭代所有项
import json
import urllib
URL_PATTERN = "http://chroniclingamerica.loc.gov/search/titles/results/" \
"?rows={rows}" \
"&year1={year1}" \
"&year2={year2}" \
"&page={page}" \
"&sort={sort}" \
"&format={format}"
rows = "1"
page = "1"
year1 = "1690"
year2 = "2016"
sort_kind = "relevance"
response_kind = "json"
url = URL_PATTERN.format(rows=rows, page=page, year1=year1, year2=year2,
sort=sort_kind, format=response_kind)
response = urllib.urlopen(url)
data = json.loads(response.read())
for item in data.get("items", []):
# Pretty print.
print(json.dumps(item, indent=4))
另外,请记住,如果您不使用某些筛选选项,您可以简化上述URL
Python的禅宗说:
美胜于丑
以及:
可读性很重要
最后-我非常喜欢相关URL中API的不一致性(混合了snake_大小写和camerCase符号):-)