Hello I have this code to load a JSON file and I want to pass values to variables:
with open('C:/files/response.json') as json_file:
data = json.load(json_file)
for item in data:
if 'XMLRESPONSE' in item:
property_values.append(item['ITEM']['TOTALQTY'])
testvalue = str(property_values[0])
print (testvalue)
But for that instance only I have the error:
“TypeError: string indices must be integers”
Also I want to call in the same way the values:
DESCRIPTION, PARTNUM, UNITPRICE, ITEMNO, VENDORDESCR
I pretend to use the same way:
if 'XMLRESPONSE' in item:
property_values2.append(item['ITEM']['DESCRIPTION'])
if 'XMLRESPONSE' in item:
property_values3.append(item['ITEM']['PARTNUM'])
if 'XMLRESPONSE' in item:
property_values4.append(item['ITEM']['UNITPRICE'])
if 'XMLRESPONSE' in item:
property_values5.append(item['ITEM']['ITEMNO'])
if 'XMLRESPONSE' in item:
property_values6.append(item['ITEM']['VENDORDESCR'])
But is obvious is not working. How can I modify the script to make it read that values?
This is the JSON file:
{
"XMLRESPONSE": {
"ITEM": {
"PARTNUM": "876666",
"UNITPRICE": "$1.50",
"ITEMNO": "55667",
"VENDORITEMNO": "1206613",
"DESCRIPTION": "tests",
"VENDORDESCR": "test",
"ERP": "$1,999.00",
"REBATEVALUE": "$0.00",
"REBATEENDDATE": null,
"ISNONSTOCK": "false",
"ISFACTORYDIRECT": "false",
"FREEFRT": "true",
"RESTRICTED": "false",
"BRANCHQTY": [
{
"BRANCH": "test",
"QTY": "0",
"INSTOCKDATE": null
},
{
"BRANCH": "test",
"QTY": "2",
"INSTOCKDATE": null
},
{
"BRANCH": "test",
"QTY": "5",
"INSTOCKDATE": null
},
{
"BRANCH": "test",
"QTY": "0",
"INSTOCKDATE": null
}
],
"TOTALQTY": "7"
},
"STATUS": "success"
}
}
I tried to use the lines of code above but I receive errors.
2
Answers
data
is a dict, makingitem
a string.You cannot index a string by a string.
You don’t need a for loop.
I suggest you use a class to parse data into, not "parallel lists"
You are trying to string into index which is not allowed in Python. When you load json you use dictionary: