pythonjson

How to remove return to line in a list in a JSON file?


In Python, I would like to get all elements from my lists BIRD_answer and my_answer in a single row:

{
    "BIRD_answer":[
        [
            0.043478260869565216
        ],
        [
            0.07042253521126761
        ],
        [
            0.11363636363636363
        ]
    ],
    "my_answer":[
        [
            "MillenniumHighAlternative",
            0.043478260869565216
        ],
        [
            "RanchodelMarHigh(Continuation)",
            0.07042253521126761
        ],
        [
            "DelAmigoHigh(Continuation)",
            0.11363636363636363
        ]
    ]
}

To give me a format like this :

    "BIRD_answer":[[0.043478260869565216],[0.07042253521126761],[0.11363636363636363]],
    "my_answer":[["MillenniumHighAlternative",0.043478260869565216],["RanchodelMarHigh(Continuation)",0.07042253521126761],["DelAmigoHigh(Continuation)",0.11363636363636363]]
}

I have already tried to use jsbeautifier but doesn't work.


Solution

  • You can do it using json.dumps

    import json
    
    data = {
        "BIRD_answer": [
            [0.043478260869565216],
            [0.07042253521126761],
            [0.11363636363636363]
        ],
        "my_answer": [
            ["MillenniumHighAlternative", 0.043478260869565216],
            ["RanchodelMarHigh(Continuation)", 0.07042253521126761],
            ["DelAmigoHigh(Continuation)", 0.11363636363636363]
        ]
    }
    
    formatted_lines = []
    
    for key, value in data.items():
        compact_value = json.dumps({key: value}, separators=(',', ':'))
        formatted_lines.append(f"    {compact_value[1:-1]}")
    
    formatted_json = "{\n" + ",\n".join(formatted_lines) + "\n}"
    
    print(formatted_json)
    

    Result :

    {
        "BIRD_answer":[[0.043478260869565216],[0.07042253521126761],[0.11363636363636363]],
        "my_answer":[["MillenniumHighAlternative",0.043478260869565216],["RanchodelMarHigh(Continuation)",0.07042253521126761],["DelAmigoHigh(Continuation)",0.11363636363636363]]
    }