How to convert JSON data into a Python tuple?

PythonProgramming

You can first convert the json to a dict using json.loads and then convert it to a python tuple using dict.items(). You can parse JSON files using the json module in Python. This module parses the json and puts it in a dict. You can then get the values from this like a normal dict. For example, if you have a json with the following content −

Example

{
   "id": "file",
   "value": "File",
   "popup": {
      "menuitem": [
         {"value": "New", "onclick": "CreateNewDoc()"},
         {"value": "Open", "onclick": "OpenDoc()"},
         {"value": "Close", "onclick": "CloseDoc()"}
      ]
   }
}

You can load it in your python program and loop over its keys in the following way −

import json
f = open('data.json')
data = json.load(f)
f.close()
print(tuple(data.items()))

Output

This will give the output −

(('id', 'file'), ('value', 'File'), ('popup', {'menuitem': [{'value': 'New', 'onclick': 'CreateNewDoc()'}, {'value': 'Open', 'onclick': 'OpenDoc()'}, {'value': 'Close', 'onclick': 'CloseDoc()'}]}))
raja
Published on 18-Apr-2018 17:01:56
Advertisements