Skip to content
Related Articles

Related Articles

How to convert JSON to Ordereddict?

Improve Article
Save Article
Like Article
  • 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.

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!