skip to Main Content

It appears to be that by default Python json module serializes a Python list using new lines between each element, like so:

"data": [
    -6.150000000000006,
    -0.5,
    0.539999999999992,
    0.5800000000000125,
    -4.6299999999999955,
    12.0,
    2.829999999999984,
    -1.4199999999999875,
    1.759999999999991,
    -1.25,

I would like to serialize the contents of this list on a single line, if possible. How can I do that?

I am using json.dumps(data, indent=4) to perform the serialization step.

2

Answers


  1. Chosen as BEST ANSWER

    One possible solution:

    Serialize the list to a string first, then serialize the remaining contents of the dictionary.

    There is a disadvantage to this:

    • The code is more complex, serialization and deserialization must be done in two steps
    • The list is now stored as a string literal rather than a list

    ... in other words it looks like this ...

    my_list: "[]"
    

    ... instead of this ...

    my_list: []
    

  2. using python version 3.8 , run this code below.
    python

    import json
    
    data = {
        "data": [-6.150000000000006,
        -0.5,
        0.539999999999992,
        0.5800000000000125,
        -4.6299999999999955,
        12.0,
        2.829999999999984,
        -1.4199999999999875,
        1.759999999999991,
        -1.25,]
    }
    
    # Serializing without indentation
    json_string = json.dumps(data)
    
    print(json_string)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search