PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Monday, August 29, 2022

[FIXED] How to convert a Python String to a dict without eval

 August 29, 2022     csv, python, string     No comments   

Issue

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?


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'}


Answered By - Amadan
Answer Checked By - David Marino (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing