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}}
]
smack cherry
  • 471
  • 3
  • 7

1 Answers1

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}}]
game0ver
  • 1,250
  • 9
  • 22