Python Forum

Full Version: json.dumps list output
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
Is it possible in python 3.8 to print list in one line rather than printing each item on new line via json.dumps? Are there any other json libraries that can do it?
json dumps converts to a dictionary.
this dictionary can be better viewed as a formatted text file.

python has a tool that you can use to convert and format JSON data
to a nicely formatted text file.

from command line, Linux format is:
cat myfile.json | python -m json.tool > myfile.txt
(Mar-16-2020, 02:23 AM)Larz60+ Wrote: [ -> ]cat myfile.json | python -m json.tool > myfile.txt
But this is for command line. I need something that will print inner lists of my dict in one line. Like here https://stackoverflow.com/questions/2626...n/54356188 The answers are pretty old there, so maybe there is a new solution?
Out of interest, why?
(Mar-16-2020, 07:52 AM)ndc85430 Wrote: [ -> ]Out of interest, why?
Well, um, I just need this format to complete the task. This is what the "customer" wants.
Ha, nice little printing exercise (one can print into file as well).

Using data from SO example:

>>> j = {'rows_parsed': [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'i']]}
>>> for k in j: 
...     print('{') 
...     print(f'{" " * 4}"{k}":  [') 
...     print(*[f'{" " * 8}{item}' for item in j[k]], sep=',\n') 
...     print(f'{" " * 4}]') 
...     print('}') 
...      
{
    "rows_parsed":  [
        ['a', 'b', 'c', 'd'],
        ['e', 'f', 'g', 'i']
    ]
}
here's my dictionary display:
    def display_dict(dictname, level=0):
        indent = " " * (4 * level)
        for key, value in dictname.items():
            if isinstance(value, dict):
                print(f'\n{indent}{key}')
                level += 1
                self.display_dict(value, level)
            else:
                print(f'{indent}{key}: {value}')
            if level > 0:
                level -= 1
It seems that there's no an easy way to achieve one line printing in .json. Thanks for the answers!
Have you looked at the documentation? https://docs.python.org/3/library/json.html
Yes, but I haven't found a way to control inner lists output without writing my own encoder
Pages: 1 2