Skip to content
TheChatArchiveThe Chat Archive
ChatGPT (model unspecified)· OpenAIHugging Face ShareLM (browser-extension contributions)

Create a code to extract json from a text that may contain general text in addition to…

  1. User

    Create a code to extract json from a text that may contain general text in addition to the json.

  2. Assistant

    Here’s a Python script that extracts JSON objects from a text, even if the text contains other unrelated content before, between, or after the JSON data: pythonCopiar códigoimport json import re

    def extract_json_from_text(text): """ Extracts all valid JSON objects or arrays from a string that may contain other text. Returns a list of parsed Python objects (dicts/lists). """ json_objects = []

    # Regex pattern that matches JSON objects {} or arrays []
    pattern = r'(\{.*?\}|\[.*?\])'
    
    # Find all candidate JSON-like substrings
    candidates = re.findall(pattern, text, re.DOTALL)
    
    for candidate in candidates:
        try:
            parsed = json.loads(candidate)
            json_objects.append(parsed)
        except json.JSONDecodeError:
            continue  # Skip anything that’s not valid JSON
    
    return json_objects
    

    Example usage

    if name == "main": sample_text = """ Here’s some text before the JSON. {"name": "Alice", "age": 30} And here’s another one: [1, 2, 3, {"key": "value"}] And here’s some text after. """

    results = extract_json_from_text(sample_text)
    for i, obj in enumerate(results, 1):
        print(f"JSON #{i}:")
        print(json.dumps(obj, indent=2))
    

    🔍 Explanation

    The regex ({.?}|[.?]) looks for either {...} or [...] blocks.

    The re.DOTALL flag allows matching across multiple lines.

    Each match is passed to json.loads() to ensure it’s valid JSON.

    Invalid matches are skipped.

    ✅ Output example For the given sample_text, the script prints: jsonCopiar códigoJSON #1: { "name": "Alice", "age": 30 } JSON #2: [ 1, 2, 3, { "key": "value" } ]

    Would you like me to modify it to extract JSON even if it’s nested or incomplete (e.g., with missing brackets or extra commas)?

  3. User

    compare two jsons to see they have the same nested structure

  4. Assistant

    Great — so you want to check if two JSON objects have the same structure, regardless of their actual values. Here’s a clean, reusable Python function that recursively compares two JSONs (dicts/lists) to see if their nested structure matches:

    pythonCopiar códigoimport json

    def have_same_structure(a, b): """ Recursively checks if two JSON-like structures have the same shape. Ignores values, focuses only on keys and nesting. """ # If both are dicts, compare keys and recurse if isinstance(a, dict) and isinstance(b, dict): if set(a.keys()) != set(b.keys()): return False return all(have_same_structure(a[k], b[k]) for k in a)

    # If both are lists, compare lengths of structure (not necessarily same length)
    elif isinstance(a, list) and isinstance(b, list):
        # Compare structure element-wise only if both have items
        if not a or not b:
            return True  # empty lists or structural placeholder
        return have_same_structure(a[0], b[0])
    
    # Otherwise, for primitive types, structure matches
    else:
        return not isinstance(a, (dict, list)) and not isinstance(b, (dict, list))
    

    def compare_json_structures(json_str1, json_str2): """ Convenience wrapper for JSON strings. """ obj1 = json.loads(json_str1) obj2 = json.loads(json_str2) return have_same_structure(obj1, obj2)

    Example usage

    if name == "main": json1 = ''' { "user": { "name": "Alice", "age": 30, "hobbies": ["reading", "gaming"] }, "active": true } '''

    json2 = '''
    {
        "user": {
            "name": "Bob",
            "age": 25,
            "hobbies": ["hiking", "music"]
        },
        "active": false
    }
    '''
    
    same = compare_json_structures(json1, json2)
    print("Same structure?", same)
    

    ✅ Output vbnetCopiar códigoSame structure? True

    If you try comparing something like: pythonCopiar códigojson3 = '{"user": {"name": "Bob", "hobbies": "music"}, "active": false}'

    You’ll get: vbnetCopiar códigoSame structure? False

    🧠 Key points

    Works for arbitrarily nested JSON (dicts/lists).

    Ignores values completely.

    Treats list elements as having the same structure if their first element has the same shape — which is typically sufficient for homogenous lists.

    Would you like me to make it more strict (e.g., ensure all list elements have identical structures, not just the first)?