[Answer]-Unable to get output as json dict

1πŸ‘

raw_input() returns a string, which is an entirely different object from inp which is a Python dictionary.

If you wanted raw_input to be treated as JSON, first parse it as such:

inp = raw_input("Enter a Dict")
inp = django.utils.simplejson.loads(inp)
django.utils.simplejson.dump(inp, f)

or parse it as a Python literal expression:

from ast import literal_eval

inp = raw_input("Enter a Dict")
inp = literal_eval(inp)
django.utils.simplejson.dump(inp, f)

0πŸ‘

You are converting the user’s input into a string. It is not a dictionary; it is a string that start with { and ends with }.

You need to parse/evaluate it as a dictionary first before converting it to json.

>>> inp = "{'a': 1, 'b': 2}"
>>> json.dumps(inp)
'"{\'a\': 1, \'b\': 2}"'
>>> import ast
>>> d = ast.literal_eval(inp)
>>> json.dumps(d)
'{"a": 1, "b": 2}'
πŸ‘€Burhan Khalid

0πŸ‘

Input = β€œ{β€˜a’:1,’b’:2}”

import ast
ast.literal_eval(Input)

OR

eval(Input)

It will work for you… πŸ™‚

Output -: {β€˜a’:1,’b’:2}

πŸ‘€Nilesh

Leave a comment