Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to convert a Python String to a dict without eval

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

How do I convert it into a dict?

>Solution :

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'}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading