使用正则表达式将python中字符串中的布尔值true转换为true
我是python新手。我有一根绳子,看起来像下面这样使用正则表达式将python中字符串中的布尔值true转换为true,python,regex,python-3.x,dictionary,Python,Regex,Python 3.x,Dictionary,我是python新手。我有一根绳子,看起来像下面这样 """[{"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":79
"""[{"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}}
]"""
我需要使用ast
将其转换为dict列表。但是它显示了由于offer
键中的false
导致的格式错误的字符串错误。
我知道python接受True
作为布尔值,而不是True
。因此,我使用re
模块将其转换为False
,但在字符串中,出现了更多的False
或true
。
我需要将字符串中所有唯一的布尔值转换为python布尔值。我不知道用regex
格式来更改它。帮我解决一些问题
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)
所需输出:
[{"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}}
]
如上文注释部分所述,您应该改用模块,更具体地说:
如上文注释部分所述,您应该改用模块,更具体地说:
您应该使用json
而不是ast
模块。如何制作..@Wiktor Stribiżew,谢谢。。你应该使用json
而不是ast
模块。如何制作..@Wiktor Stribiżew,谢谢。。它起作用了
>>> 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}}]