skip to Main Content

I have a list of JSON dict that is not in valid JSON format.
They are all listed in a text file

"{'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'}"

what I would like to have is

 {"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"}

to have a valid JSON

3

Answers


  1. I use replaceAll() for this purpose

    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("'","""))
    
    Login or Signup to reply.
  2. i think the code like this

    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))
    

    images

    Login or Signup to reply.
  3. You can use regex to replace the " (opening double quotes) with { and " (closing double quotes) with } and then use replace to replace all the single quotes with double quotes and then use json.loads(some_str) to convert it to JSON dict and you can append it to a new list.

    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.loads(n)
        new_data.append(n)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search