Open In App

How to convert Ordereddict to JSON?

In this article, we will learn How to convert a nested OrderedDict to JSON? Before this we must go through  some concepts:

To define the OrderedDict, we are using the collections module in python.






# import package
from collections import OrderedDict
  
# define OrderedDict
od1 = OrderedDict([('1','one'), 
                   ('2','two')])
  
# display dictionary
print(type(od1))
print(od1)

Output:

<class 'collections.OrderedDict'>
OrderedDict([('1', 'one'), ('2', 'two')])

To convert OrderedDict to JSON, we are using json.dumps()






# import package
from collections import OrderedDict
import json
  
# define OrderedDict
od1 = OrderedDict([('1','one'), 
                   ('2','two')])
  
# check type i.e; OrderedDict
print(type(od1))
  
# convert to json
od1 = json.dumps(od1)
  
# check type i.e; str
print(type(od1))
  
# view value
print(od1)

Output
<class 'collections.OrderedDict'>
<class 'str'>
{"1": "one", "2": "two"}

We can give indent value to show the dictionary pattern.




# import package
from collections import OrderedDict
import json
  
# define OrderedDict
od1 = OrderedDict([('1', 'one'),
                   ('2', 'two')])
  
# check type i.e; OrderedDict
print(type(od1))
  
# convert to json
od1 = json.dumps(od1, indent=4)
  
# check type i.e; str
print(type(od1))
  
# view value
print(od1)

Output:

<class 'collections.OrderedDict'>
<class 'str'>
{
    "1": "one",
    "2": "two"
}

Article Tags :