Python,将JSON迭代与多个键和值进行比较

时间:2015-12-07 18:52:11

标签: python json parsing for-loop key

我无法比较来自JSON的2次迭代以匹配asset Ids和所有匹配资产的打印值,具有多个键和多个值我很困惑有效地执行此操作。

我可以比较一下吗?

  

assetId = key

  

asset = value [" asset"] [" id"]

来自不同的迭代,如果所有资产都匹配,那么打印所有匹配资产编号的(item,listingId,subTotal)?

不是完整的JSON,而是我需要使用的部分:

{ 
  "success": true,
  "more": false,
  "listinginfo": {
    "719811220882156383": {
      "listingid": "719811220882156383",
      "converted_price": 657,
      "converted_fee": 97,
      "asset": {
        "currency": 0,
        "appid": 730,
        "contextid": "2",
        "id": "4495490578",
        "amount": "1",
      }
    },
    "719811220882158733": {
      "listingid": "719811220882158733",
      "converted_price": 49,
      "converted_fee": 6,
      "asset": {
        "currency": 0,
        "appid": 730,
        "contextid": "2",
        "id": "2778717097",
        "amount": "1",
      }
    },
  "purchaseinfo": [    
  ],
  "assets": {
    "730": {
      "2": {
        "4495490578": {
          "currency": 0,
          "appid": 730,
          "contextid": "2",
          "id": "4495490578",
          "classid": "1389958217",
          "instanceid": "188530139",
          "amount": "1",
          "status": 2,
          "original_amount": "1",
          "background_color": "",
          "icon_url": "-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpot7HxfDhjxszJemkV09-5lpKKqPrxN7LEmyVQ7MEpiLuSrYmnjQO3-UdsZGHyd4_Bd1RvNQ7T_FDrw-_ng5Pu75iY1zI97bhLsvQz",
          "icon_url_large": "-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgpot7HxfDhjxszJemkV09-5lpKKqPrxN7LEm1Rd6dd2j6eQ9N2t2wK3-ENsZ23wcIKRdQE2NwyD_FK_kLq9gJDu7p_KyyRr7nNw-z-DyIFJbNUz",
          "name": "AK-47 | Redline",
          "name_color": "D2D2D2",
          "type": "Classified Rifle",
          "market_name": "AK-47 | Redline (Field-Tested)",
          "market_hash_name": "AK-47 | Redline (Field-Tested)",
          "owner": 0
        },
        "2778717097": {
          "currency": 0,
          "appid": 730,
          "contextid": "2",
          "id": "2778717097",
          "classid": "720294710",
          "instanceid": "188530139",
          "amount": "1",
          "status": 2,
          "original_amount": "1",
          "background_color": "",
          "icon_url": "-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgposr-kLAtl7PLZTjlH7du6kb-FlvD1DLPUl31IppF3jLvC8d2i2lKx-BVpN2_3IdPDcwJqMF7Z_VS7yOy-0JbuucvKyiF9-n51aSXb4FU",
          "icon_url_large": "-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXH5ApeO4YmlhxYQknCRvCo04DEVlxkKgposr-kLAtl7PLZTjlH7du6kb-FlvD1DLPUl31I18lwmO7Eu9jzjga3r0JrYT-mJ9CQJgA6ZA2G-1XqkOjmgpO5tZ-YnHIxv3Yh5izD30vgRbaAlsY",
          "name": "Desert Eagle | Naga",
          "name_color": "D2D2D2",
          "type": "Restricted Pistol",
          "market_name": "Desert Eagle | Naga (Battle-Scarred)",
          "market_hash_name": "Desert Eagle | Naga (Battle-Scarred)",
          "owner": 0
        },
        "4487026121": {
          "currency": 0,
          "appid": 730,
          "contextid": "2",
          "id": "4487026121",
          "classid": "1428441554",
          "instanceid": "0",
          "amount": "1",
          "status": 2,
          "original_amount": "1",
          "background_color": "",
          "icon_url": "-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXU5A1PIYQNqhpOSV-fRPasw8rsUFJ5KBFZv668FFMu1aPMI24auITjxteJwPXxY72AkGgIvZAniLjHpon2jlbl-kpvNjz3JJjVLFG9rl1YLQ",
          "tradable": 0,
          "name": "Operation Breakout Weapon Case",
          "name_color": "D2D2D2",
          "type": "Base Grade Container",
          "market_name": "Operation Breakout Weapon Case",
          "market_hash_name": "Operation Breakout Weapon Case",
          "owner": 0
        }
      }
    }
  }
 }
}

解析我能够做到这一点:

            InfoJson = json.loads(response)
            assetInfoJson = InfoJson["assets"]["730"]["2"]
            for key, value in assetInfoJson.iteritems():
                assetId = key
                try:
                    image = value["icon_url"]
                    item = value["market_hash_name"]
                except KeyError:
                  continue

            listingInfoJson = InfoJson["listinginfo"]
            for key, value in listingInfoJson.iteritems():
                listingId = key
                try:
                    subTotal = value["converted_price"]
                    feeAmount = value["converted_fee"]
                    asset = value["asset"]["id"]
                except KeyError:
                  continue
            if assetId == asset:
                print ("Found Matching asset :",assetId)
                print ("Found Matching name : %s, listingid : %s, subtotal : %s" % (item, listingId, subTotal))

不幸的是,只有当最后一个assetId与两次迭代中的第一个资产匹配时,这种方式才能比较两个匹配资产ID的完整列表。

1 个答案:

答案 0 :(得分:1)

您正在错误地使用for循环。由于两个循环都处于同一级别,因此assetIdimageitem的值将是上次循环成功运行时分配的值。

第二个for循环也出现了类似的问题。

最后,if条件只会比较每个列表中最后一个元素的值。

问题的解决方案是使用in运算符在正确的字典中查找给定的ID

InfoJson = json.loads(response)
assetInfoJson = InfoJson["assets"]["730"]["2"]
listingInfoJson = InfoJson["listinginfo"]

for key, value in listingInfoJson.iteritems():
    listingId = key
    try:
        subTotal = value["converted_price"]
        feeAmount = value["converted_fee"]
        asset = value["asset"]["id"]
    except KeyError:
      continue

    if asset in assetInfoJson:
        # Get asset details if it's present in the assetInfoJson dict
        assetInfo = assetInfoJson[asset]
        try:
            image = assetInfo["icon_url"]
            item = assetInfo["market_hash_name"]
        except KeyError:
          continue

        print ("Found Matching asset :",assetId)
        print ("Found Matching name : %s, listingid : %s, subtotal : %s" % (item, listingId, subTotal))