JSON zu Python-Objekt
Der folgende Code erstellt rekursiv dynamische Attribute mit den Schlüsseln der Objekte.
JSON-Objekt - fb_data.json
:
{
"name": "John Smith",
"hometown": {
"name": "New York",
"id": 123
},
"list": [
"a",
"b",
"c",
1,
{
"key": 1
}
],
"object": {
"key": {
"key": 1
}
}
}
Bei der Umwandlung haben wir 3 Fälle:
- Listen
- dicts (neues Objekt)
-
bool, int, float und 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)
Die Schlüssel-Wert-Paare sind nun Attribute - Objekte.
Ausgabe:
John Smith
New York
123
1
1
JSON als Code einfügen
Unterstützt TypeScript
, Python
, Go
, Ruby
, C#
, Java
, Swift
, Rust
, Kotlin
, C++
, Flow
, Objective-C
, JavaScript
, Elm
y JSON Schema
.
- Interaktive Generierung von Typen und (De-)Serialisierungscode aus JSON, JSON Schema und TypeScript
- JSON/JSON-Schema/TypeScript als Code einfügen
![enter image description here]()
quicktype
leitet aus JSON-Beispieldaten Typen ab und gibt dann stark typisierte Modelle und Serialisierer für die Arbeit mit diesen Daten in Ihrer gewünschten Programmiersprache aus.
Ausgabe:
# Generated by https://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
Diese Erweiterung ist kostenlos erhältlich in der Visual Studio Code-Marktplatz .