gpt4 book ai didi

python - 在文本中动态双引号 "keys"以在 python 中形成有效的 JSON 字符串

转载 作者:行者123 更新时间:2023-12-04 16:06:31 24 4
gpt4 key购买 nike

我正在处理网页上 JS 变量中包含的文本,并使用正则表达式提取字符串,然后使用 json.loads() 将其转换为 Python 中的 JSON 对象。

我遇到的问题是未加引号的“键”。现在,我正在对每个字符串中的每个键进行一系列替换(下面的代码),但我想要的是在将字符串传递到 json.loads() 之前动态识别任何未加引号的键。

示例 1 : 字符后没有空格

json_data1 = '[{storeName:"testName",address:"12345 Road",address2:"Suite 500",city:"testCity",storeImage:"http://www.testLink.com",state:"testState",phone:"999-999-9999",lat:99.9999,lng:-99.9999}]'

示例 2 : 字符后有空格

json_data2 = '[{storeName: "testName",address: "12345 Road",address2: "Suite 500",city: "testCity",storeImage: "http://www.testLink.com",state: "testState",phone: "999-999-9999",lat: 99.9999,lng: -99.9999}]'

示例 3 后有空格,: 字符

json_data3 = '[{storeName: "testName", address: "12345 Road", address2: "Suite 500", city: "testCity", storeImage: "http://www.testLink.com", state: "testState", phone: "999-999-9999", lat: 99.9999, lng: -99.9999}]'

示例 4 后有空格:字符和换行符

json_data4 = '''[
{
storeName: "testName",
address: "12345 Road",
address2: "Suite 500",
city: "testCity",
storeImage: "http://www.testLink.com",
state: "testState",
phone: "999-999-9999",
lat: 99.9999, lng: -99.9999
}]'''

我需要创建模式来识别哪些是键,而不是包含字符的随机字符串值,例如 storeImage 中的字符串链接。换句话说,我想动态查找键并用双引号将它们引用以使用 json.loads() 并返回有效的 JSON 对象。

我目前正在以这种方式替换文本中的每个键

content = re.sub('storeName:', '"storeName":', content)
content = re.sub('address:', '"address":', content)
content = re.sub('address2:', '"address2":', content)
content = re.sub('city:', '"city":', content)
content = re.sub('storeImage:', '"storeImage":', content)
content = re.sub('state:', '"state":', content)
content = re.sub('phone:', '"phone":', content)
content = re.sub('lat:', '"lat":', content)
content = re.sub('lng:', '"lng":', content)

以表示有效 JSON 的字符串形式返回

json_data = [{"storeName": "testName", "address": "12345 Road", "address2": "Suite 500", "city": "testCity", "storeImage": "http://www.testLink.com", "state": "testState", "phone": "999-999-9999", "lat": 99.9999, "lng": -99.9999}]

我确信有更好的方法可以做到这一点,但我一直无法找到或想出一个正则表达式模式来处理这些问题。非常感谢任何帮助!

最佳答案

像这样的东西应该可以完成工作:([{,]\s*)([^"':]+)(\s*:)

替换为:\1"\2"\3

示例:https://regex101.com/r/oV0udR/1

关于python - 在文本中动态双引号 "keys"以在 python 中形成有效的 JSON 字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48524894/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com