2

I am trying to create a JSON file from a dictionary containing dictionaries and lists. I want the lists to be horizontal, not vertical. I want to make the JSON also human-readable and I cannot figure out how or whether it is actually possible to save the JSON in such way.

I am saving the dictionary with a function with following parameters:

def dict2json(dic, file_name):
    with open(file_name, 'w') as fp:
        json.dump(dic, fp, indent=4)

The list in question is a simple python list [1, 2, 3, 4, 5, 6, 7, 8, 9, 10].

Section of the current output:

The key values here take too much space and would be impractical for human-readability:

"density": {
        "measurements": [
            {
                "values": [
                    1, 
                    2, 
                    3, 
                    4, 
                    5, 
                    6, 
                    7, 
                    8, 
                    9, 
                    10
                ], 
                "type": "con", 
                "params": {
                    "sigma": 10, 
                    "mean": 100
                }, 
                "meas_ID": 1
            }
        ]
    },

Desired ouptut:

I would like for the key values to print horizontally as follows:

"density": {
        "measurements": [
            {
                "values": [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 
                "type": "con", 
                "params": {
                    "sigma": 10, 
                    "mean": 100
                }, 
                "meas_ID": 1
            }
        ]
    },

What I tried:

I have tried to change indent to 0 and other numbers but that did not help. I also tried the ensure_ascii = True as a parameter but that hasn't solved the problem either. Do I need to write my own JsonEncoder?

NOTE:

The indents shown in the JSON snippets are not actually 4 but something more, that is due to copy-paste. The indents are actually 4 in my IDE.

martineau
  • 119,623
  • 25
  • 170
  • 301

0 Answers0