python - Python在JSON中查找包含在单词/字符串中的单引号
问题描述
我正在将json数据解析为python中的SQL查询,并且需要注意用双引号替换单引号,因为我得到的数据的符号是错误的(我无法改变它)。我遇到的问题是,一些字符串是英文文本并包含单引号。
'comment': 'bla bla it's you're can't bla bla',
我如何只替换书面文本中的那些而不是定义属性的那些?这个正则表达式会是什么样子?
解决方案
虽然我同意您对问题的所有评论,但作为一个练习,我试图从您拥有的内容中获取一个有效的 json 字符串。似乎可以通过涉及字符串操作的几个步骤来完成:
bad = "'comment': 'bla not, really, a comment: bla it's you're can't bla bla',"
# note that bad has colons, commas and single quotes/apostrophes in it
one = bad.replace("': '",'": "') #separate the key from the value
two = one.replace("'",'"',1) #replace the single quote on the left side of the key with a double quote
#the following lines were lifted from https://stackoverflow.com/a/54945804/9448090
#replace the single quote on the right side of the value with a double quote; drop the last comma:
removal = "'"
reverse_removal = removal[::-1]
replacement = '"'
reverse_replacement = replacement[::-1]
three = two[::-1].replace(reverse_removal, reverse_replacement, 1)[::-1].replace('",','"')
good = "{"+three+"}" #final formatting for json
json.loads(good)
输出:
{'comment': "bla not, really, a comment: bla it's you're can't bla bla"}
推荐阅读
- google-apps-script - 如何在 Google Apps 脚本中的导出库中传递项目授权
- html - Muli 字体未正确渲染
- laravel - 带有连接查询的 Laravel Scope
- python - Python Logger 记录两次
- oracle - 在 WHERE 子句中使用 CASE 语句 - PL/SQL
- javascript - 我怎样才能在中心获得“滚动”按钮?
- javascript - CSS显示时的布局变化:从block变为none后从none变为block
- powershell - 当字符串包含反引号时,Like 运算符返回 false
- c# - 使用令牌验证用户并在本地调用 REST API 共享点
- javascript - 在every() 中跳过第一个元素?