pythonjsonjsonlines

Loading JSONL file as JSON objects


I want to load a JSONL file as JSON objects in python. Is there an easy way to do so?


Solution

  • The splitlines would address that problem for you, so In general the code below will work for you:

    import json
    
    result = [json.loads(jline) for jline in jsonl_content.splitlines()]
    

    If that's the response object the result would be:

    result = [json.loads(jline) for jline in response.read().splitlines()]
    

    NOTE

    splitlines() treats line breaks differently than JSON's escape requirements. Specifically, splitlines() splits on Unicode Line Separator (\u2028), while JSON allows this character to remain unescaped in strings. When using json.dump with ensure_ascii=False, Python will emit \u2028 unescaped in strings.