我一直在摸不着为什么它不打印我需要的json内容。谁知道我做错了什么?
这是字典
> "listinginfo": {
> "438309609514180554": {
> "listingid": "438309609514180554",
> "price": 35,
> "fee": 4,
> "publisher_fee_app": 730,
> "publisher_fee_percent": "0.10000000149011612",
> "currencyid": "2003",
> "steam_fee": 1,
> "publisher_fee": 3,
> "converted_price": 50,
> "converted_fee": 7,
> "converted_currencyid": "2020",
> "converted_steam_fee": 2,
> "converted_publisher_fee": 5,
> "converted_price_per_unit": 50,
> "converted_fee_per_unit": 7,
> "converted_steam_fee_per_unit": 2,
> "converted_publisher_fee_per_unit": 5,
> "asset": {
> "currency": 0,
> "appid": 730,
> "contextid": "2",
> "id": "1579403640",
> "amount": "1",
> "market_actions": [
> {
代码+我需要我想要打印的键的值:
while 1:
r = requests.get(url, headers=headers)
listingInfoStr = r.content
result= ujson.loads(listingInfoStr)
listingInfoJson= result['listinginfo']
for listingdata in listingInfoJson:
print listingdata.get('listingId')
print listingdata.get('subTotal')
print listingdata.get('feeAmount')
print listingdata.get('totalPrice')
time.sleep(10)
感谢您的时间。
答案 0 :(得分:2)
您可以使用requests.Response.json方法来解析JSON:
r = requests.get(url, headers=headers)
listingInfoJson = r.json()['listinginfo']
答案 1 :(得分:0)
我运行了你的代码,它看起来像listingInfoJson作为dict返回而不是列表。因此,当你迭代它时,它只是拉动键。
您在unicode对象上调用.get方法,这会给您一个AttributeError。您可以通过不同的方式运行此代码:
for listingdata in listingInfoJson:
print listingInfoJson[listingdata].get('listingid')
print listingInfoJson[listingdata].get('subTotal')
print listingInfoJson[listingdata].get('feeAmount')
print listingInfoJson[listingdata].get('totalPrice')
或更好的方式(编辑评论):
if listingInfoJson:
for key, value in listingInfoJson.iteritems():
print value.get('listingid')
print value.get('subTotal')
print value.get('feeAmount')
print value.get('totalPrice')
else:
print "listingInfoJson is empty"
我还要检查您的关键值,listingId
应为listingid