【问题标题】:Converting double quotes within JSON values to single quotes?将 JSON 值中的双引号转换为单引号?
【发布时间】:2018-01-07 15:30:53
【问题描述】:

我有一个如下所示的 json 字符串列表:

[
    {
    "info": "https://google.com/athens",
    "locationdetails": "Greece"
    ...
    },
    {
    "info": "italytourism.com",
    "locationdetails": "Gardens of "Little Italy" indoors"
    ...
    }
    ...
]

其中的一些 json 值在其中包含双引号(例如“Little Italy”,这会产生错误,因为在 python 中,双引号(或转义字符)中只能使用单引号。我是想知道通过这个 json 字符串和键列表并将值字符串内的双引号转换为单引号的最佳方法是什么。有人建议使用 json.dumps(jsonlist) 来解决问题,但这没有用对我来说..感谢您的帮助!

【问题讨论】:

  • 这是无效的 json。您首先需要对这些引号进行转义。
  • 你确定吗?我已经能够像普通 json 一样访问键和值。但如果是这种情况,我们需要将其中的 "" 替换为单引号,以便它可以是有效的 json 并用于其他功能。有没有一种简单的方法可以做到这一点?
  • 嗯...有趣。你能分享一下似乎有效的代码吗?另外,我不确定是否有......正则表达式可能有效。你怎么得到这个json?
  • 这是我写的另一个函数的一部分:for dict in jsonlist: try: dict["info"]= "pastes location variable here" dict["url"]=urlparse(dict["url"]).hostname except KeyError: pass return jsonlink 它适用于 json 列表直到它遇到了值中有双引号的问题......这就是为什么我想知道如何替换那些。 @coldspeed
  • 所以你手动生成了上面的 JSON 字符串,没有 json 库?如果是这样,您正在为自己创造大量工作。

标签: python json list replace double-quotes


【解决方案1】:

如 cmets 中所述,您的示例不是有效的 JSON。使用json 库时,请注意引号已正确转义,并且数据可以从序列化到/从 JSON 格式往返。

import json

data = [
    {
    'info': 'https://google.com/athens',
    'locationdetails': 'Greece'
    },
    {
    'info': 'italytourism.com',
    'locationdetails': 'Gardens of "Little Italy" indoors'
    }
]

j = json.dumps(data,indent=2)
print(j)

data2 = json.loads(j)
print(data2 == data)
[
  {
    "info": "https://google.com/athens", 
    "locationdetails": "Greece"
  }, 
  {
    "info": "italytourism.com", 
    "locationdetails": "Gardens of \"Little Italy\" indoors"
  }
]
True

【讨论】:

    【解决方案2】:

    这个 RegEx 在给定的有限示例中修复了您的错误 json,但我不希望它对于所有可以想象的示例都是健壮的。例如,它假定您的值中只有字母数字字符和空格,除了有问题的双引号字符。

    import re
    import json
    
    jsonString = """
    [
        {
        "info": "https://google.com/athens",
        "locationdetails": "Greece"
    
        },
        {
        "info": "italytourism.com",
        "locationdetails": "Gardens of "Little Italy" indoors"
        }
    ]
    """
    data = json.loads(re.sub(r'": "([\s\w]*)"([\s\w]+)"([\s\w]*)"(,?)', r'": "\1' + "'" + r'\2' + "'" + r'\3"\4', jsonString))
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-01-17
      • 2013-01-20
      • 2018-11-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多