Store list in json Python
Python JSON
Previous
Next
JSON is a syntax for storing and exchanging data. Show JSON is text, written with JavaScript object notation. JSON in PythonPython has a built-in package called json, which can be used to work with JSON data. ExampleImport the json module:
import json
Parse JSON - Convert from JSON to PythonIf you have a JSON string, you can parse it by using the json.loads() method. The result will be a Python dictionary. ExampleConvert from JSON to Python:
import json
Try it Yourself »
Convert from Python to JSONIf you have a Python object, you can convert it into a JSON string by using the json.dumps() method. ExampleConvert from Python to JSON:
import json
Try it Yourself »
You can convert Python objects of the following types, into JSON strings:
ExampleConvert Python objects into JSON strings, and print the values:
import json
Try it Yourself »
When you convert from Python to JSON, Python objects are converted into the JSON (JavaScript) equivalent:
ExampleConvert a Python object containing all the legal data types:
import json
Try it Yourself »
Format the ResultThe example above prints a JSON string, but it is not very easy to read, with no indentations and line breaks. The json.dumps() method has parameters to make it easier to read the result: ExampleUse the indent parameter to define the numbers of indents:
json.dumps(x, indent=4)
Try it Yourself »
You can also define the separators, default value is (", ", ": "), which means using a comma and a space to separate each object, and a colon and a space to separate keys from values: ExampleUse the separators parameter to change the default separator:
json.dumps(x, indent=4, separators=(". ", " = "))
Try it Yourself »
Order the ResultThe json.dumps() method has parameters to order the keys in the result: ExampleUse the sort_keys parameter to specify if the result should be sorted or not:
json.dumps(x, indent=4, sort_keys=True)
Try it Yourself »
Previous
Next
|