Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

How to convert JSON to Ordereddict?

  • Difficulty Level : Basic
  • Last Updated : 24 Jan, 2021

The full-form of JSON is JavaScript Object Notation. It means that a script (executable) file which is made of text in a programming language, is used to store and transfer the data. Python supports JSON through a built-in package called json. To use this feature, we import the json package in Python script. The text in JSON is done through quoted-string which contains a value in key-value mapping within { }. It is similar to the dictionary in Python.

An OrderedDict is a dictionary subclass that remembers the order that keys were first inserted. The only difference between dict() and OrderedDict() is that: OrderedDict preserves the order in which the keys are inserted. A regular dict doesn’t track the insertion order and iterating it gives the values in an arbitrary order.

 Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.  

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course

In this article we are going to discuss various methods to convert JSON to Ordereddict.



Method #1

By specifying the object_pairs_hook argument to JSONDecoder.

Python




# import required modules
import json
from collections import OrderedDict
  
# assign json file
jsonFile = '{"Geeks":1, "for": 2, "geeks":3}'
print(jsonFile)
  
# convert to Ordereddict
data = json.JSONDecoder(object_pairs_hook=OrderedDict).decode(jsonFile)
print(data)


Output:

{"Geeks":1, "for": 2, "geeks":3}
OrderedDict([(u'Geeks', 1), (u'for', 2), (u'geeks', 3)])

Method #2

By passing the JSON data as a parameter to json.loads().

Python




# import required modules
import json
from collections import OrderedDict
  
# assign json file
jsonFile = '{"Geeks":1, "for": 2, "geeks":3}'
print(jsonFile)
  
# convert to Ordereddict
data = json.loads(jsonFile, 
                  object_pairs_hook=OrderedDict)
print(data)


Output:

{"Geeks":1, "for": 2, "geeks":3}
OrderedDict([(u'Geeks', 1), (u'for', 2), (u'geeks', 3)])



My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!