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

Python 将JSON值中的双引号转换为单引号?,python,json,list,replace,double-quotes,Python,Json,List,Replace,Double Quotes,我有一个json字符串列表,如下所示: [ { "info": "https://google.com/athens", "locationdetails": "Greece" ... }, { "info": "italytourism.com", "locationdetails": "Gardens of "Little Italy" indoors" ... } ... ] 本文中的一些json值中

我有一个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格式来回转换

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)

这个正则表达式在给出的有限示例中修复了错误的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))

这不是有效的json。您需要先对这些引号进行转义。您确定吗?我可以像普通json一样访问键和值。但是如果是这样,我们需要替换“”在它里面用单引号括起来,这样它就可以成为一个有效的json并在其他函数中使用。有没有一个简单的方法可以做到这一点?嗯…很有趣。你能分享一下似乎有效的代码吗?还有,我不确定是否有…正则表达式可以工作。你是如何得到这个json的?这是我在jsonlist:t中为dict编写的另一个函数的一部分:
ry:dict[“info”]=“在此处粘贴位置变量”dict[“url”]=urlparse(dict[“url”]).hostname except KeyError:pass return jsonlink
它在json列表中工作,直到遇到在值中有双引号的问题…这就是为什么我想知道如何替换它们。@coldspeeds您是否在没有
json
库的情况下手动生成了上面的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))