Home > Blockchain >  How to convert a Python String to a dict without eval
How to convert a Python String to a dict without eval

Time:07-07

I have a string like this

"{""netPrice"":251.6,""totalPrice"":299.4,""calculatedTaxes"":[{""tax"":47.8,""taxRate"":19.0,""price"":251.6,""extensions"":[]}],""taxRules"":[{""taxRate"":19.0,""percentage"":100.0,""extensions"":[]}],""positionPrice"":232.0,""rawTotal"":299.4,""taxStatus"":""net""}"

and i need it to be an dict like {'netPrice': 251.6, 'totalPrice':299.4, and so on} but since it hast the double quotes eval and json doesnt work for this. I import that string out of a csv file with

with open('order.csv', 'r') as csv_datei:
    for row in csv_datei:

so i cant get it in a cleaner format as far as i know. (the String is the row)

How do I convert it into a dict?

CodePudding user response:

As suggested in comments, this seems to be a JSON that has been placed inside CSV. Standard CSV surrounds string values with double quotes ("..."), and uses double double-quotes ("") to denote a double-quote character (") inside a string.

As it is doubly encoded, pass it through both of the relevant parsers:

import csv
import json

with open('order.csv', 'r') as csv_datei:
    for row in csv.reader(csv_datei):
        data = json.loads(row[0])
        print(data)

# => {'netPrice': 251.6, 'totalPrice': 299.4, 'calculatedTaxes': [{'tax': 47.8, 'taxRate': 19.0, 'price': 251.6, 'extensions': []}], 'taxRules': [{'taxRate': 19.0, 'percentage': 100.0, 'extensions': []}], 'positionPrice': 232.0, 'rawTotal': 299.4, 'taxStatus': 'net'}
  • Related