rev*_*evy 4 python regex json double-quotes single-quotes
我有一个文件,在每一行上我都有这样的文字(代表电影的演员):
[{'cast_id': 23, 'character': "Roger 'Verbal' Kint", 'credit_id': '52fe4260c3a36847f8019af7', 'gender': 2, 'id': 1979, 'name': 'Kevin Spacey', 'order': 5, 'profile_path': '/x7wF050iuCASefLLG75s2uDPFUu.jpg'}, {'cast_id': 27, 'character': 'Edie's Finneran', 'credit_id': '52fe4260c3a36847f8019b07', 'gender': 1, 'id': 2179, 'name': 'Suzy Amis', 'order': 6, 'profile_path': '/b1pjkncyLuBtMUmqD1MztD2SG80.jpg'}]
Run Code Online (Sandbox Code Playgroud)
我需要将其转换为有效的json字符串,从而仅将必要的单引号转换为双引号(例如,不得转换单词Verbal周围的单引号,也不应转换文本中最终的撇号)。
我正在使用python 3.x. 我需要找到一个仅将正确的单引号转换为双引号的正则表达式,从而使整个文本产生有效的json字符串。任何的想法?
小智 6
首先,您作为示例给出的那行是不可解析的!… 'Edie's Finneran' …包含语法错误,无论如何。
假设您可以控制输入,则可以简单地使用eval()读取文件。(尽管如此,在那种情况下,人们会想知道为什么您不能首先生成有效的JSON…)
>>> f = open('list.txt', 'r')
>>> s = f.read().strip()
>>> l = eval(s)
>>> import pprint
>>> pprint.pprint(l)
[{'cast_id': 23,
'character': "Roger 'Verbal' Kint",
...
'profile_path': '/b1pjkncyLuBtMUmqD1MztD2SG80.jpg'}]
>>> import json
>>> json.dumps(l)
'[{"cast_id": 23, "character": "Roger \'Verbal\' Kint", "credit_id": "52fe4260ca36847f8019af7", "gender": 2, "id": 1979, "name": "Kevin Spacey", "order": 5, "rofile_path": "/x7wF050iuCASefLLG75s2uDPFUu.jpg"}, {"cast_id": 27, "character":"Edie\'s Finneran", "credit_id": "52fe4260c3a36847f8019b07", "gender": 1, "id":2179, "name": "Suzy Amis", "order": 6, "profile_path": "/b1pjkncyLuBtMUmqD1MztDSG80.jpg"}]'
Run Code Online (Sandbox Code Playgroud)
如果您无法控制输入,这将非常危险,因为它使您容易遭受代码注入攻击。
我不能过分强调最好的解决方案是首先生成有效的JSON。
小智 1
import ast
def getJson(filepath):
fr = open(filepath, 'r')
lines = []
for line in fr.readlines():
line_split = line.split(",")
set_line_split = []
for i in line_split:
i_split = i.split(":")
i_set_split = []
for split_i in i_split:
set_split_i = ""
rev = ""
i = 0
for ch in split_i:
if ch in ['\"','\'']:
set_split_i += ch
i += 1
break
else:
set_split_i += ch
i += 1
i_rev = (split_i[i:])[::-1]
state = False
for ch in i_rev:
if ch in ['\"','\''] and state == False:
rev += ch
state = True
elif ch in ['\"','\''] and state == True:
rev += ch+"\\"
else:
rev += ch
i_rev = rev[::-1]
set_split_i += i_rev
i_set_split.append(set_split_i)
set_line_split.append(":".join(i_set_split))
line_modified = ",".join(set_line_split)
lines.append(ast.literal_eval(str(line_modified)))
return lines
lines = getJson('test.txt')
for i in lines:
print(i)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5526 次 |
| 最近记录: |