首页 文章

将JSON值中的双引号转换为单引号?

提问于
浏览
0

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

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

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

2 回答

  • 1

    如评论中所述,您的示例不是有效的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”:“希腊”
    },
    {
    “info”:“italytourism.com”,
    “locationdetails”:“花园”小意大利“室内”
    }
    ]
    真正

  • 1

    这个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))
    

相关问题