修复不带双引号的JSON dict

fhg3lkii  于 2023-08-08  发布在  其他
关注(0)|答案(3)|浏览(78)

我有一个不是有效JSON格式的JSON dict列表。它们都列在一个文本文件中

"{'name': 'Alice', 'age': 30, 'tasks' [1, 2, 3], 'description': 'writer'}"
"{'name': 'Bob', 'age': 33, 'tasks' [4, 5, 6], 'description': 'runner'}"
"{'name': 'Kelly', 'age': 23, 'tasks' [7, 8, 9], 'description': 'singer'}"

字符串
我想要的是

{"name": "Alice", "age": 30, "tasks" [1, 2, 3], "description": "writer"}
 {"name": "Bob", "age": 33, "tasks" [4, 5, 6], "description": "runner"}
 {"name": "Kelly", "age": 23, "tasks" [7, 8, 9], "description": "singer"}


一个有效的JSON

t3psigkw

t3psigkw1#

为此我使用replaceAll()

let obj = [
"{'name': 'Alice', 'age': 30, 'tasks' [1, 2, 3], 'description': 'writer'}",
"{'name': 'Bob', 'age': 33, 'tasks' [4, 5, 6], 'description': 'runner'}",
"{'name': 'Kelly', 'age': 23, 'tasks' [7, 8, 9], 'description': 'singer'}"
]

let jsonObj = JSON.parse(JSON.stringify(obj).replaceAll("\'","\""))

字符串

m3eecexj

m3eecexj2#

我认为这样的代码

import json

data = [
    "{'name': 'Alice', 'age': 30, 'tasks': [1, 2, 3], 'description': 'writer'}",
    "{'name': 'Bob', 'age': 33, 'tasks': [4, 5, 6], 'description': 'runner'}",
    "{'name': 'Kelly', 'age': 23, 'tasks': [7, 8, 9], 'description': 'singer'}"
]

def fix_json(json_str):
    json_str = json_str.strip().replace("'", '"')  # Replace single quotes with double quotes
    json_str = json_str.replace('"tasks" [', '"tasks": [')  # Add colon after "tasks"
    return json_str

# Fix the JSON format of each JSON string
fixed_data = [fix_json(json_str) for json_str in data]

# Convert the fixed JSON strings into a valid JSON array
json_array = '[' + ','.join(fixed_data) + ']'

# Load the JSON array
result = json.loads(json_array)

# Print the valid JSON
print(json.dumps(result, indent=2))

字符串


的数据

p3rjfoxz

p3rjfoxz3#

您可以使用regex将**"(双引号)替换为{,将(双引号)替换为}**,然后使用replace将所有单引号替换为双引号,然后使用json.dumps(some_str)将其转换为JSON字符串。你可以把它添加到一个新的列表中,或者根据自己的喜好使用它。

import re, json
data = ["{'name': 'Alice', 'age': 30, 'tasks': [1, 2, 3], 'description':'writer'}",
"{'name': 'Bob', 'age': 33, 'tasks': [4, 5, 6], 'description': 'runner'}",
"{'name': 'Kelly', 'age': 23, 'tasks': [7, 8, 9], 'description': 'singer'}"]
new_data = []
for n in data:
    n = re.sub('^".+','{',n)
    n = re.sub('$"."','}',n) 
    n = n.replace("'",'"')
    n = json.dumps(n)
    new_data.append(n)

字符串

相关问题