DEV Community

oladejo abdullahi
oladejo abdullahi

Posted on

convert python to json

How to convert python to json

In one of my previous articles I discussed how to convert JSON to python data. But what if we have a python data to be converted to json so that we share the data to third party it is very simple logic.
Convert from Python to JSON
If you have a Python object o, you can convert it into a JSON string by using the json.dumps() method.

Example

#Convert from Python to JSON:
import json # you must import this
# a Python object (dict):
Biodata = {
  "name": "maxwizard",
  "age": 22,
  "country": "Nigeria",
  "married": False,
  "divorced": False,
  "children":None
}

# convert into JSON:
jsonData= json.dumps(Biodata)
# the result is a JSON string:
print(jsonData)
Enter fullscreen mode Exit fullscreen mode

OUTPUT:

{"name": "maxwizard", "age": 22, "country": "Nigeria", "married": false, "divorced": false, "children": null}
Enter fullscreen mode Exit fullscreen mode

Notice: false,none and true start with capital letter in python while small letter in json. Also None become null in json.
so when you convert from Python to JSON, Python objects are converted into the JSON (JavaScript) equivalent:

Python--> JSON

dict------> Object

list------> Array

tuple-----> Array

str-------> String

int-------> Number

float-----> Number

True------> true

False-----> false

None -----> null

Let's try another technical example
Example

import json
#python data
biodata = {
  "name": "Abdullah",
  "age": 22,
  "married": True,
  "divorced": False,
  "religon":"muslim",
  "children": ("Ahmod","joy"),
  "pets": None,
  "cars": [
    {"model": "Camry 303", "mpg": 27.5},
    {"model": "Ford Edge", "mpg": 24.1}
  ]
}
jsondata=json.dumps(biodata)
print(jsondata)
Enter fullscreen mode Exit fullscreen mode

OUTPUT:

{"name": "Abdullah", "age": 22, "married": true, "divorced": false, "religon": "muslim", "children": ["Ahmod", "joy"], "pets": null, "cars": [{"model": "Camry 303", "mpg": 27.5}, {"model": "Ford Edge", "mpg": 24.1}]}
Enter fullscreen mode Exit fullscreen mode

if you look at the output of the program above. there is a json string but it is not very easy to read, with no indentations and line breaks so that will leads us to something called Formatting.

HOW TO FORMAT THE RESULT

The json.dumps() method has parameters to make it easier to read the result: so we make use of the indent parameter to define the numbers of indents:

Example

#python data
biodata = {
  "name": "Abdullah",
  "age": 22,
  "married": True,
  "divorced": False,
  "religon":"muslim",
  "children": ("Ahmod","joy"),
  "pets": None,
  "cars": [
    {"model": "Camry 303", "mpg": 27.5},
    {"model": "Ford Edge", "mpg": 24.1}
  ]
}
jsonData=json.dumps(biodata, indent=4)
print(jsonData)
Enter fullscreen mode Exit fullscreen mode

OUTPUT:

{
    "name": "Abdullah",
    "age": 22,
    "married": true,
    "divorced": false,
    "religon": "muslim",
    "children": [
        "Ahmod",
        "joy"
    ],
    "pets": null,
    "cars": [
        {
            "model": "Camry 303",
            "mpg": 27.5
        },
        {
            "model": "Ford Edge",
            "mpg": 24.1
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

wow did you see how it looks? But that is not all
You can also add the separators, default value to be (", ", ": "), which means using a comma and a space to separate each object, and a colon and a space to separate keys from values:

Example

#python data
biodata = {
  "name": "Abdullah",
  "age": 22,
  "married": True,
  "divorced": False,
  "religon":"muslim",
  "children": ("Ahmod","joy"),
  "pets": None,
  "cars": [
    {"model": "Camry 303", "mpg": 27.5},
    {"model": "Ford Edge", "mpg": 24.1}
  ]
}
jsonData=json.dumps(biodata, indent=4,separators=(". ", " = "))
print(jsonData)
Enter fullscreen mode Exit fullscreen mode

OUTPUT:

{
    "name" = "Abdullah". 
    "age" = 22. 
    "married" = true. 
    "divorced" = false. 
    "religon" = "muslim". 
    "children" = [
        "Ahmod". 
        "joy"
    ]. 
    "pets" = null. 
    "cars" = [
        {
            "model" = "Camry 303". 
            "mpg" = 27.5
        }. 
        {
            "model" = "Ford Edge". 
            "mpg" = 24.1
        }
    ]
}
Enter fullscreen mode Exit fullscreen mode

you can see that we have able to put assign value for each of the variable just like javascript usully look like. Let me tell you this, you can even sort all the data so that they are in order by adding sort_keys parameter.

Example

#python data
biodata = {
  "name": "Abdullah",
  "age": 22,
  "married": True,
  "divorced": False,
  "religon":"muslim",
  "children": ("Ahmod","joy"),
  "pets": None,
  "cars": [
    {"model": "Camry 303", "mpg": 27.5},
    {"model": "Ford Edge", "mpg": 24.1}
  ]
}
jsonData=json.dumps(biodata, indent=4,separators=(". ", " = "),sort_keys=True)
print(jsonData)
Enter fullscreen mode Exit fullscreen mode

OUTPUT:

{
    "age" = 22. 
    "cars" = [
        {
            "model" = "Camry 303". 
            "mpg" = 27.5
        }. 
        {
            "model" = "Ford Edge". 
            "mpg" = 24.1
        }
    ]. 
    "children" = [
        "Ahmod". 
        "joy"
    ]. 
    "divorced" = false. 
    "married" = true. 
    "name" = "Abdullah". 
    "pets" = null. 
    "religon" = "muslim"
}
Enter fullscreen mode Exit fullscreen mode

Did you see the result? it even make sense enough! if you find this article helpful then follow me and like. you can click here to read how to convert json to python.

Top comments (0)