试图打印JSON值

时间:2015-10-27 18:25:23

标签: python json

我有戴尔网站的JSON输出,我试图访问这些值,但实际上很难访问这些值。

例如,我检索了以下JSON:

    {   
    "GetAssetWarrantyResponse": {
        "GetAssetWarrantyResult": {
            "Faults": null,
            "Response": {
                "DellAsset": {
                    "MachineDescription": "T350, New Balance",
                    "ShipDate": "2010-05-04",
                    "ServiceTag": "89M1",
                    "OrderNumber": 518,
                    "LocalChannel": 25,
                    "AssetParts": {
                        "@nil": "true"
                    },
                    "CountryLookupCode": 11,
                    "ItemClassCode": "V02",
                    "IsDuplicate": "false",
                    "ParentServiceTag": {
                        "@nil": "true"
                    },
                    "CustomerNumber": 1121,
                    "Warranties": {
                        "Warranty": [
                            {   
                                "StartDate": "2011-05-05",
                                "EndDate": "2013-05-04",
                                "ServiceProvider": "U",
                                "ServiceLevelCode": "D",
                                "ItemNumber": "992-82",
                                "EntitlementType": "EXTENDED",
                                "ServiceLevelDescription": "Next Business Day Support",
                                "ServiceLevelGroup": 5
                            },
                            {   
                                "StartDate": "2010-05-04",
                                "EndDate": "2011-05-04",
                                "ServiceProvider": "U",
                                "ServiceLevelCode": "N",
                                "ItemNumber": "993-0",
                                "EntitlementType": "INITIAL",
                                "ServiceLevelDescription": "Next Business Day Support",
                                "ServiceLevelGroup": 5
                            }
                        ]
                    }
                }
            }
        }
    }
}

例如,如果我想检索" ServiceTag"的价值。我怎么能在python中得到它?出于某种原因,当我尝试做以下事情时:

raw_data = urllib2.urlopen('https://json.url')
djson = raw_data.read()
djdata = (json.dumps(json.loads(djson), indent=4))
print djdata['GetAssetWarrantyResponse']['GetAssetWarrantyResult']['Faults']['Response']['DellAsset'][0]['ServiceTag']

我得到了:

    Traceback (most recent call last):
  File "./warranty.py", line 35, in <module>
    print djdata['GetAssetWarrantyResponse']['GetAssetWarrantyResult']['Faults']['Response']['DellAsset'][0]['ServiceTag']
TypeError: string indices must be integers, not str

1 个答案:

答案 0 :(得分:5)

使用json.loads创建包含JSON信息的python dict。

然后,就像任何python dict一样访问它。

import json

mydict = json.loads(json_response)

print mydict['GetAssetWarrantyResponse']['GetAssetWarrantyResult']['Response']['DellAsset']['ServiceTag']