Home > Back-end >  How do I get a specific element from a json string?
How do I get a specific element from a json string?

Time:09-11

I have a JSON string (not in a file): [{'x': 403.5, 'y': 53.0, 'width': 117, 'height': 106, 'class': 'fruitflies', 'confidence': 0.626}, {'x': 446.0, 'y': 189.0, 'width': 124, 'height': 130, 'class': 'fruitflies', 'confidence': 0.528}], now as you can see, the entire string is in a list. Inside the list is the dictionary. There are 2 dictionaries in the list and I want to get how many dictionaries there are (it's only 2 for this example) and I want to get the 'confidence' values of both of them. They aren't in a file, just in one line.

CodePudding user response:

d_list = [{'x': 403.5, 'y': 53.0, 'width': 117, 'height': 106, 'class': 'fruitflies', 'confidence': 0.626}, {'x': 446.0, 'y': 189.0, 'width': 124, 'height': 130, 'class': 'fruitflies', 'confidence': 0.528}]
confidence_vals = [d['confidence'] for d in d_list]

Something like this?

CodePudding user response:

Best option is to create a plain object from the string representation and getting the length property of the array for free. Or reduce the array to get the sum of confidences.

PyNative JSON parsing

CodePudding user response:

If you just want to get the value, you can slice the list and get the value of the key from each list index:

lst = [{'x': 403.5, 'y': 53.0, 'width': 117, 'height': 106, 'class': 'fruitflies', 'confidence': 0.626}, {'x': 446.0, 'y': 189.0, 'width': 124, 'height': 130, 'class': 'fruitflies', 'confidence': 0.528}]

confidence_1 = lst[0]['confidence']
confidence_2 = lst[1]['confidence']

# 0.626
# 0.528

Or:

lst = [{'x': 403.5, 'y': 53.0, 'width': 117, 'height': 106, 'class': 'fruitflies', 'confidence': 0.626}, {'x': 446.0, 'y': 189.0, 'width': 124, 'height': 130, 'class': 'fruitflies', 'confidence': 0.528}]

for c in lst: print(c['confidence'])

# 0.626
# 0.528
  • Related