【问题标题】:Python find single quotation marks in JSON which are contained in words/stringPython在JSON中查找包含在单词/字符串中的单引号
【发布时间】:2020-03-06 14:12:19
【问题描述】:

我正在将 json 数据解析为 python 中的 SQL 查询,并且需要注意用双引号替换单引号,因为我得到的数据的符号是错误的(我无法更改) .我遇到的问题是,一些字符串是英文文本并包含单引号。

'comment': 'bla bla it's you're can't bla bla',

我如何只替换书面文本中的那些而不是定义属性的那些?正则表达式会是什么样子?

【问题讨论】:

  • TL;DR:这与有效的 JSON 相去甚远。如果它应该是,这个 really 必须固定在始发端。如果那是不可能的,那么你有点 SOL。不能保证完全可以安全地解析这样的内容。
  • 我真的很想知道这些可疑 JSON 的来源。就像在几乎所有编程语言都存在完美的库时,他们认为可以将这些怪物释放到野外一样。
  • 我真的不知道为什么我会从我正在访问的 API 中得到这个无效的 JSON,但我无法在接收之前更改它。只是认为可能有解决方法。
  • 要么您以某种方式误解了您从该 API 获得的信息,要么您真的需要与该 API 的作者取得联系,并与他们谈谈一些道理。
  • 我正在访问的 API 是 Google 的 API 之一。我无法提供任何转储,因为它是敏感数据,但我刚刚通过 Google 的示例请求进行了检查,我得到了相同的无效 json。在他们的支持下进行检查。也许我错过了一些问题。

标签: python json regex parsing escaping


【解决方案1】:

虽然我同意您的问题的所有 cmets,但作为练习,我试图从您拥有的内容中获取有效的 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"}

【讨论】:

    【解决方案2】:

    假设您假设字符串中没有逗号和/或冒号,您可以通过将:, 之间的所有内容作为字符串来恢复。例如,这可以通过使用正则表达式拆分来实现。

    In [1]: s = "'comment1': 'bla bla it's you're can't bla bla','comment2': 'bla bla it's you're can't bla bla',"
    
    In [2]: r = re.compile(r"[:,]")
    
    In [3]: r.split(s)
    Out[3]:
    ["'comment1'",
     " 'bla bla it's you're can't bla bla'",
     "'comment2'",
     " 'bla bla it's you're can't bla bla'",
     '']
    
    

    当然,这是一个很大的“如果”。如果您的字符串甚至有可能包含逗号/冒号字符,那么deceze 是正确的并且您是 SOL。

    一般来说,这个问题没有解决办法。要了解这一点,请考虑以下(有些人为的)示例。

     ... 'comment': 'this is', 'my comments': 'Hi', 
    

    如果允许包裹在 ' 中的字符串包含 ' ,则无法判断这是 'comment': "this is', 'my comments': 'Hi'", 还是 'comment': "this is", 'my comments': "Hi", ...

    【讨论】:

    • 感谢您的帮助。我已经知道这些字符串中实际上有逗号和/或冒号,所以是的。我是 SOL。
    猜你喜欢
    • 2013-01-08
    • 1970-01-01
    • 2018-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-28
    • 1970-01-01
    • 2021-10-11
    相关资源
    最近更新 更多