Home > Blockchain >  How to convert this output to json and fetch the values
How to convert this output to json and fetch the values

Time:10-18

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.

CodePudding user response:

You can remove the newline characters and apply literal_eval:

from ast import literal_eval

directreceipts = ['{\n "quantityOfUnits": 1500,\n "ownerOnDespatch": "100038",\n "packSize": 3\n}', '{\n "quantityOfUnits": 2500,\n "ownerOnDespatch": "100038",\n "packSize": 4\n}']
directreceipts_list = [literal_eval(i.replace('\n', '').strip()) for i in directreceipts]

Outputs a list of dicts:

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

CodePudding user response:

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}]
  • Related