JSON conversion: Built-in functions to convert a string in JSON format to a python object
Often web services, files or any other data exchange mechanism utilizes the JSON format as a standard to shared data between different processes. In this context, it is important to a programming language to provide functions to parse these JSON strings to a native object, enabling the data processing in a more feasible way then the string processing.
For python programming
language there is a module name json, which contains a method to load a JSON
string, but it needs an additional parameter that is the “hook function”, a
function to handle how each object will de translated to object.
import json
#https://docs.python.org/3/library/json.html
from types
import SimpleNamespace
#https://docs.python.org/3/library/types.html
print("### JSON to object example with multilevel objects ####")
data = '{"name": "Ramza
Beoulve", "details": {"firstName": "Ranza",
"lastName": "Beoulve"}}'
# Parse JSON into an object with
attributes corresponding to its keys.
#SimpleNamespace: function that creates dynamically names for object properties
obj = json.loads(data, object_hook = lambda obj:
SimpleNamespace( **obj )) # ** spread operator
print("Name:", obj.name)
print("details.firstName" , obj.details.firstName, "details.lastName", obj.details.lastName)
This hook
function is defined in the example above using the lambda syntax. It is
basically a function that receives as input an object and returns the new
produced object. For performing this processing we utilize the spread operator
(**) which basically clone the object properties in a new object, and then the
SimpleNamespace function, which is able to based on original property names
create new properties in the produced object. At the end the json.loads
function returns new objects that contains all properties that are on JSON string,
even when it is another objects (multi level) or arrays (several objects).
The
complete code with more examples is available to be downloaded here:
https://github.com/rafaelqg/code/blob/main/map_reduce_reduce_example.py
You may see
a video class about this video here:
Comments
Post a Comment