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

2024-10-01 13:38:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个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)来解决问题,但这对我没用……谢谢你的帮助!在


Tags: 字符串httpsinfocomjson列表googlelittle
2条回答

这个RegEx在给定的有限示例中修复了您的错误json,但我不希望它对所有可能的示例都是健壮的。E、 g.它假设值中除了双引号字符外,只有字母数字字符和空格。在

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格式往返。在

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

相关问题 更多 >