How to convert string to json in Python

Created
Modified

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 = '''{
  "name":"Android", 
  "version":13
}'''

d = json.loads(s)
print(d)

print(json.loads('"\\"foo\\bar"'))
{u'version': 13, u'name': u'Android'}
"foar

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)}])
print(s)
["foo", {"bar": ["baz", null, 0.1, 2]}]

Translations

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:
infile
The JSON file to be validated or pretty-printed.
outfile
Write the output of the infile to the given outfile. Otherwise, write it to sys.stdout.
--sort-keys
Sort the output of dictionaries alphabetically by key.
--no-ensure-ascii
Disable escaping of non-ascii characters, see json.dumps() for more information.
--json-lines
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