JSON to python object
The follwing code creates dynamic attributes with the objects keys recursively.
JSON object - fb_data.json
:
{
"name": "John Smith",
"hometown": {
"name": "New York",
"id": 123
},
"list": [
"a",
"b",
"c",
1,
{
"key": 1
}
],
"object": {
"key": {
"key": 1
}
}
}
On the conversion we have 3 cases:
- lists
- dicts [new object]
- bool, int, float and str
import json
class AppConfiguration[object]:
def __init__[self, data=None]:
if data is None:
with open["fb_data.json"] as fh:
data = json.loads[fh.read[]]
else:
data = dict[data]
for key, val in data.items[]:
setattr[self, key, self.compute_attr_value[val]]
def compute_attr_value[self, value]:
if isinstance[value, list]:
return [self.compute_attr_value[x] for x in value]
elif isinstance[value, dict]:
return AppConfiguration[value]
else:
return value
if __name__ == "__main__":
instance = AppConfiguration[]
print[instance.name]
print[instance.hometown.name]
print[instance.hometown.id]
print[instance.list[4].key]
print[instance.object.key.key]
Now the key, value pairs are attributes - objects.
output:
John Smith
New York
123
1
1
Paste JSON as Code
Supports TypeScript
, Python
, Go
, Ruby
, C#
, Java
, Swift
,
Rust
, Kotlin
, C++
, Flow
, Objective-C
, JavaScript
, Elm
, and JSON Schema
.
- Interactively generate types and [de-]serialization code from JSON, JSON Schema, and TypeScript
- Paste JSON/JSON Schema/TypeScript as code
quicktype
infers types from sample JSON data, then outputs strongly
typed models and serializers for working with that data in your desired programming language.
output:
# Generated by //quicktype.io
#
# To change quicktype's target language, run command:
#
# "Set quicktype target language"
from typing import List, Union
class Hometown:
name: str
id: int
def __init__[self, name: str, id: int] -> None:
self.name = name
self.id = id
class Key:
key: int
def __init__[self, key: int] -> None:
self.key = key
class Object:
key: Key
def __init__[self, key: Key] -> None:
self.key = key
class FbData:
name: str
hometown: Hometown
list: List[Union[Key, int, str]]
object: Object
def __init__[self, name: str, hometown: Hometown, list: List[Union[Key, int, str]], object: Object] -> None:
self.name = name
self.hometown = hometown
self.list = list
self.object = object
This extension is available for free in the Visual Studio Code Marketplace.
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 the value in key-value mapping within { }.
Reading From JSON
It’s pretty easy to load a JSON
object in Python. Python has a built-in package called json, which can be used to work with JSON data. It’s done by using the JSON module, which provides us with a lot of methods which among loads[] and load[] methods are gonna help us to read the JSON file.
Deserialization of JSON
The Deserialization of JSON means the conversion of JSON objects into their respective Python objects. The load[]/loads[] method is used for it. If you have used JSON data from another program
or obtained as a string format of JSON, then it can easily be deserialized with load[]/loads[], which is usually used to load from string, otherwise, the root object is in list or dict. See the following table given below.
object | dict |
array | list |
string | str |
null | None |
number [int] | int |
number [real] | float |
true | True |
false | False |
json.load[]: json.load[] accepts file object, parses the JSON data, populates a Python dictionary with the data and returns it back to you.
Syntax:
json.load[file object]
Example: Suppose the JSON file looks like this:
We want to read the content of this file. Below is the implementation.
Python3
import
json
f
=
open
[
'data.json'
]
data
=
json.load[f]
for
i
in
data[
'emp_details'
]:
print
[i]
f.close[]
Output:
json.loads[]:
If you have a JSON string, you can parse it by using the json.loads[] method.json.loads[] does not take the file path, but the file contents as a string, using fileobject.read[] with json.loads[] we can return the content of the file.
Syntax:
json.loads[jsonstring] #for Json string json.loads[fileobject.read[]] #for fileobject
Example: This example shows reading from both string and JSON file. The file shown above is used.
Python3
import
json
a
=
'{"name": "Bob", "languages": "English"}'
y
=
json.loads[a]
print
[
"JSON string = "
, y]
print
[]
f
=
open
[
'data.json'
,
"r"
]
data
=
json.loads[f.read[]]
for
i
in
data[
'emp_details'
]:
print
[i]
f.close[]
Output: