1

I am new to python. I have a string which looks like below

 """[{"key":"aadsas","doc":{"uniq_id":"false key","retail_price":799,"offer":false}},{"key":"aadsas","doc":{"uniq_id":"false key","retail_price":799,"offer":true}},{"key":false,"doc":{"uniq_id":"false key","retail_price":799,"offer":true}}
]"""

I need to convert it to list of dict using ast. But it shows malformed string error due to false in offer key. I know python accepts True as a Boolean value and not true. So I am using re module to convert it to False but in the String, there are more false or true occured in it.
I need all the unique boolean value in the string to python boolean values. I don't know the regex format to change it. Help me with some solutions.

import re, ast 
a= """[{"key":"aadsas","doc":{"uniq_id":"false key","retail_price":799,"offer":false}},{"key":"aadsas","doc":{"uniq_id":"false key","retail_price":799,"offer":true}},{"key":false,"doc":{"uniq_id":"false key","retail_price":799,"offer":true}}
]"""
a = ast.literal_eval(a)
print(a)

Required Output:

[{"key":"aadsas","doc":{"uniq_id":"false key","retail_price":799,"offer":False}},{"key":"aadsas","doc":{"uniq_id":"false key","retail_price":799,"offer":True}},,{"key":False,"doc":{"uniq_id":"false key","retail_price":799,"offer":True}}
]
4
  • 7
    You should use json instead of ast module. Commented Dec 6, 2019 at 12:10
  • How to make it.. Commented Dec 6, 2019 at 12:11
  • 2
    ideone.com/NjnSZN Commented Dec 6, 2019 at 12:12
  • @Wiktor Stribiżew , Thanks.. it worked Commented Dec 6, 2019 at 12:19

1 Answer 1

3

As mentioned in the comment section above, you should use json module instead, and more specifically json.loads:

>>> l="""[{"key":"aadsas","doc":{"uniq_id":"false key","retail_price":799,"offer":false}},{"key":"aadsas","doc":{"uniq_id":"false key","retail_price":799,"offer":true}},{"key":false,"doc":{"uniq_id":"false key","retail_price":799,"offer":true}} ]"""
>>>
>>> import json
>>> json.loads(l)
[{'key': 'aadsas', 'doc': {'uniq_id': 'false key', 'retail_price': 799, 'offer': False}}, {'key': 'aadsas', 'doc': {'uniq_id': 'false key', 'retail_price': 799, 'offer': True}}, {'key': False, 'doc': {'uniq_id': 'false key', 'retail_price': 799, 'offer': True}}]
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.