w3resource

Python JSON: Convert Python object to JSON data

Python JSON: Exercise-2 with Solution

Write a Python program to convert Python object to JSON data.

Sample Solution:-

Python Code:

import json
# a Python object (dict):
python_obj = {
  "name": "David",
  "class":"I",
  "age": 6  
}
print(type(python_obj))
# convert into JSON:
j_data = json.dumps(python_obj)

# result is a JSON string:
print(j_data)

Output:

<class 'dict'>
{"name": "David", "class": "I", "age": 6}
 

Flowchart:

Flowchart: Convert Python object to JSON data.

Python Code Editor:


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to convert JSON data to Python object.
Next: Write a Python program to convert Python object to JSON data.

What is the difficulty level of this exercise?

Test your Python skills with w3resource's quiz


Python: Tips of the Day

Python: Unknown Arguments Using *arguments

If your function can take in any number of arguments then add a * in front of the parameter name:

def myfunc(*arguments):
 for a in arguments:
   print a
myfunc(a)
myfunc(a,b)
myfunc(a,b,c)