1
print(type(directreceipts))
print(directreceipts)

o/p

1
2
<class 'list'>

['{\n "quantityOfUnits": 1500,\n "ownerOnDespatch": "100038",\n "packSize": 3\n}', '{\n "quantityOfUnits": 2500,\n "ownerOnDespatch": "100038",\n "packSize": 4\n}']

want to convert the list of strings to dictionary and access the values and also want to eleminate the \n.

2 Answers 2

2

You don't need to try to remove \n here. Just parse the string with json.

import json
directreceipts = [json.loads(d) for d in directreceipts]

Output:

[{'quantityOfUnits': 1500, 'ownerOnDespatch': '100038', 'packSize': 3},
 {'quantityOfUnits': 2500, 'ownerOnDespatch': '100038', 'packSize': 4}]

You can access the values like,

Single-value access,

In [1]: directreceipts[0]['quantityOfUnits']
Out[1]: 1500

Ideally, iterate through and access the values

In [2]: for item in directreceipts:
    ...:     print(item['quantityOfUnits'])
    ...: 
1500
2500

To find the sum of those values, Using list comprehension.

In [3]: sum([item['quantityOfUnits'] for item in directreceipts])
Out[3]: 4000
Sign up to request clarification or add additional context in comments.

3 Comments

how do i fetch the value of quantity of units here ?
how do i sum up the values which i get from the output for item in directreceipts: print(item['quantityOfUnits']) 1500 + 2500 = 4000 should be my o/p
How can i fetch only date from this 2022-10-05T07:08:55.8197232 my o/p should look like this 2022-10-05
0

try this

list_object[0].encode("utf-8").decode()

or you can try this one also :

import json
json.loads(list_object[0])

2 Comments

No it din't work. o/p ---- resp = directreceipts[0].encode("utf-8").decode() AttributeError: 'dict' object has no attribute 'encode'
resp = json.loads(directreceipts[0]) print(resp) TypeError: the JSON object must be str, bytes or bytearray, not dict

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.