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

问题描述:

我有JSON字符串列表,看起来像这样:将JSON值中的双引号转换为单引号?

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

一些在这个JSON值有双引号中他们的(如“小意大利”,并且创建了一个错误,因为在Python只有单引号可以在双引号内使用(或者是一个转义字符)我想知道通过这个json字符串和键列表的最好方法是什么,并将双引号内的值字符串转换为单引号。建议使用json.dumps(jsonlist)来解决这个问题,但这并不适用于我..感谢您的帮助!

+7

这是无效的json。您需要将这些引号从头开始。 –

+0

你确定吗?我已经能够像普通的json那样访问键和值。但是如果是这种情况,我们需要将其中的“”替换为单引号,以便它可以是有效的json并用于其他函数中。有没有简单的方法来做到这一点? – nm44

+1

嗯......有趣。你能分享一下似乎有用的代码吗?另外,我不确定是否有...正则表达式可能工作。你如何得到这个json? –

正如评论中所述,您的示例是无效的JSON。使用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 

这个表达式维修在有限的例子你的坏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))