How to endcode and decode Json in python

Json is used to data transfer between server and web application.Learn more about json from here. json module is used for json encoding and decoding in python.

Convert JSON to a Python dictionary.

To convert JSON to a Python dictionary we will use json.loads function.

import json json_data = '{"name": "tutsway", "city": "delhi"}' py_obj = json.loads(json_data) print py_obj["name"] print py_obj["city"]

OutPut

tutsway delhi

Convert Python dictionary to a JSON object.

To convert Python dictionary to a JSON object we will use json.dumps function.

import json from decimal import Decimal d = {} d["name"] = "tutsway" d["city"] = "delhi" print json.dumps(d, ensure_ascii=False)

OutPut

{"city": "delhi", "name": "tutsway"}

Convert JSON to Python List.

To convert JSON to a Python dictionary we will use json.loads function and .

import json array = '{"cities": ["delhi", "goa", "kanpur"]}' data = json.loads(array) print data for element in data['drinks']: print element

OutPut

{u'drinks': [u'delhi', u'goa', u'kanpur']} delhi goa kanpur

Copyright © 2017 by tutsway. All Rights Reserved.