I have this function. I want to be able to use the data in the first json file to populate data in the second json file There will be a lot of manipulation in the first json file and I dont want to repeat it in the second file. Here is my code
import xmltodict
import pprint
import json
def testbobo():
variable = "zombie"
jsonfile = {
"apiStatusInfo": {
"apiStatus": variable,
"apiStatusCode": 100,
"apiDescription": "Error with folder 'Admin'",
"apiErrorCode": 404,
"apiErrorDescription": [
{
"reason": "invalid_parameter",
"name": "item",
"message": "Invalid value 'd_1097790'. not found"
}
]
}
}
json_object2 = json.dumps(jsonfile, indent=4)
print("First json file")
print(jsonfile)
json_object = json.loads(json_object2)
jsonfile2 = {
"apiStatusInfo": {
"apiStatus": json_object['apiStatusInfo']['apiStatus'],
"apiStatusCode": json_object['apiStatusInfo']['apiStatusCode'],
"apiDescription": json_object['apiStatusInfo']['apiDescription'],
"apiErrorCode": json_object['apiStatusInfo']['apiErrorCode'],
"apiErrorDescription": [
{
"reason": json_object['apiStatusInfo']['apiErrorDescription']['reason'],
"name": json_object['apiStatusInfo']['apiErrorDescription']['name'],
"message": json_object['apiStatusInfo']['apiErrorDescription']['message']
}
]
}
}
json_result_second = json.dumps(jsonfile2, indent=4)
print("Second json file - must be the same with first")
print(json_result_second)
testbobo()
Everything works until I got to the apiErrorDescription section of the second json file. I was just getting this error message below
"reason": json_object['apiStatusInfo']['apiErrorDescription']['reason'],
TypeError: list indices must be integers or slices, not str
What am I doing wrong?
CodePudding user response:
In your json json_object['apiStatusInfo']['apiErrorDescription']
holds a list of dicts, you are trying to access it as if it were just a dict. This should work: json_object['apiStatusInfo']['apiErrorDescription'][0]['reason']
. You will need to do that for the following two lines as well.