-2

I have developed a python function. It returns a large object in one line (similar to the example, only ten times larger)

{'a':{'b':1,'c':2,'d':{'e':{'f':3}}}}

How do I make the returned object automatically come in formatted form? Like this:

{
  'a': {
    'b': 1,
    'c': 2,
    'd': {
      'e': {
        'f': 3
      }
    }
  }
}
Paganini
  • 178
  • 2
  • 12
  • It is unclear what you mean by formatted form. Why would you need formatted form? For user to read easily or? In your question, what is in both snippets are the same. Perhaps some context? If you are trying to make it user readable, perhaps you should reconsider what your function outputs. You could use an xmlwriter or a proper json format to get better results. – Jason Chia Mar 30 '21 at 08:03

1 Answers1

-1

json.dumps()

import json

obj = {'a':{'b':1,'c':2,'d':{'e':{'f':3}}}}

print( json.dumps(obj, indent = 2) )

If the dictionary is initially created as a string then:

obj = """{'a':{'b':1,'c':2,'d':{'e':{'f':3}}}}"""

print( json.dumps(eval(obj), indent = 2) )
Paganini
  • 178
  • 2
  • 12
  • 1
    `eval` is rarely the right option, see https://stackoverflow.com/q/1832940/3001761. In this case you should use `ast.literal_eval`. – jonrsharpe Mar 30 '21 at 08:06