How to convert string to json in Python


Decoding JSON

To convert string to json in Python, use the json.loads() function. The json.loads() is a built-in Python function that accepts a valid json string and returns a dictionary to access all elements. The json.loads() function is used to parse valid JSON string into dictionary.

import json

s = '''{

d = json.loads(s)

{u'version': 13, u'name': u'Android'}

Encoding JSON

To convert string to json in Python, use the json.dumps() function.

import json

s = json.dumps(['foo', {'bar': ('baz', None, 0.1, 2)}])
["foo", {"bar": ["baz", null, 0.1, 2]}]


Performs the following translations in decoding by default:

object dict
array list
string str
number (int) int
number (real) float
true True
false False
null None

Using json.tool Command Line Interface

Using json.tool from the shell to validate and pretty-print:

Python pretty
echo '{"json":"obj"}' | python -m json.tool
  "json": "obj"

json.tool Options

The json.tool module provides a simple command line interface to validate and pretty-print JSON objects.

Command line options:
The JSON file to be validated or pretty-printed.
Write the output of the infile to the given outfile. Otherwise, write it to sys.stdout.
Sort the output of dictionaries alphabetically by key.
Disable escaping of non-ascii characters, see json.dumps() for more information.
Parse every input line as separate JSON object.
--indent, --tab, --no-indent, --compact
Mutually exclusive options for whitespace control.
-h, --help
Show the help message.

Related Tags