Open In App

How to convert JSON to Ordereddict?

Last Updated : 24 Jan, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

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)])


Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads