Reputation: 55
I want you to ask for your help.
I need to browse folder with json files and I need to search for one attribute with specific value.
Here is my code:
def listDir():
fileNames = os.listdir(FOLDER_PATH)
for fileName in fileNames:
print(fileName)
with open('C:\\Users\\Kamčo\\Desktop\\UBLjsons\\' + fileName, 'r') as json_file:
data = json.load(json_file)
data_json = json.dumps(data, indent=2, sort_keys=True)
print(data_json)
for line in data_json:
if line['ID'] == 'Kamilko':
print("try") #just to be sure it accessed to this
I am getting this error: TypeError: string indices must be integers
I also tried to search for a solution here but it didnt help me.
Here is my JSON
{
"Invoice": {
"@xmlns": "urn:oasis:names:specification:ubl:schema:xsd:Invoice-2",
"@xmlns:cac": "urn:oasis:names:specification:ubl:schema:xsd:CommonAggregateComponents-2",
"@xmlns:cbc": "urn:oasis:names:specification:ubl:schema:xsd:CommonBasicComponents-2",
"ID": "Kamilko",
"IssueDate": "2020-02-09",
"OrderReference": {
"ID": "22"
},
"InvoiceLine": {
"Price": {
"PriceAmount": {
"@currencyID": "EUR",
"#text": "23.50"
},
"BaseQuantity": {
"@unitCode": "C62",
"#text": "1"
}
}
}
}
}
do you have any idea how to do it?
Upvotes: 0
Views: 65
Reputation: 6043
You've loaded your file in using json.load(...)
. That'll convert the JSON data into a Python dictionary that you can use to access elements:
if data["Invoice"]["OrderReference"]["ID"] == 22:
print("try")
Note that you might want to check the relevant keys exist along the way, in case the structure of your file varies, or you could catch the KeyError
that'll come up if the key doesn't exist, using try/except
.
Some more background:
When you then call json.dumps(...)
, you're taking that handy python structure and converting it back into a hard-to-understand string again. I don't think you want or need to do this.
The specific error you have is because dumps
has created a string. You're then trying to access an element of that string using the [ ]
operator. Strings can only be indexed using integers, e.g. mystr[4]
, so Python doesn't understand what you're asking it to do with data_json["ID"]
.
Upvotes: 1