martes, 30 de enero de 2018

JSON encoding and decoding with Python



Introduction
JSON (JavaScript Object Notation) is frequently used between a server and a web application. An example of JSON data:
{
    "persons": [
        {
            "city": "Seattle", 
            "name": "Brian"
        }, 
        {
            "city": "Amsterdam", 
            "name": "David"
        }
    ]
}
The json module enables you to convert between JSON and Python Objects.

JSON conversion examples

Convert JSON to Python Object (Dict)
To convert JSON to a Python dict use this:
import json
 
json_data = '{"name": "Brian", "city": "Seattle"}'
python_obj = json.loads(json_data)
print python_obj["name"]
print python_obj["city"]
Convert JSON to Python Object (List)
JSON data can be directly mapped to a Python list.
import json
 
array = '{"drinks": ["coffee", "tea", "water"]}'
data = json.loads(array)
 
for element in data['drinks']:
    print element
Convert JSON to Python Object (float)
Floating points can be mapped using the decimal library.
import json
from decimal import Decimal
 
jsondata = '{"number": 1.573937639}'
 
x = json.loads(jsondata, parse_float=Decimal)
print x['number']
Convert JSON to Python Object (Example)
JSON data often holds multiple objects, an example of how to use that below:
import json
 
json_input = '{"persons": [{"name": "Brian", "city": "Seattle"}, {"name": "David", "city": "Amsterdam"} ] }'
 
try:
    decoded = json.loads(json_input)
 
    # Access data
    for x in decoded['persons']:
        print x['name']
 
except (ValueError, KeyError, TypeError):
    print "JSON format error"
Convert Python Object (Dict) to JSON
If you want to convert a Python Object to JSON use the json.dumps() method.
import json
from decimal import Decimal
 
d = {}
d["Name"] = "Luke"
d["Country"] = "Canada"
 
print json.dumps(d, ensure_ascii=False)
# result {"Country": "Canada", "Name": "Luke"}
Converting JSON data to Python objects 
JSON data can be converted (deserialized) to Pyhon objects using the json.loads()function.  A table of the mapping:
JSONPython
objectdict
arraylist
stringstr
number (int)int
number (real)float
trueTrue
falseFalse
nullNone

Pretty printing

If you want to display JSON data you can use the json.dumps() function.
import json
 
json_data = '{"name": "Brian", "city": "Seattle"}'
python_obj = json.loads(json_data)
print json.dumps(python_obj, sort_keys=True, indent=4)
https://pythonspot.com/en/json-encoding-and-decoding-with-python/

No hay comentarios:

Publicar un comentario