JSON 到 python 对象
以下代码使用对象键递归创建动态属性。
JSON 对象 - fb_data.json:
{
"name": "John Smith",
"hometown": {
"name": "New York",
"id": 123
},
"list": [
"a",
"b",
"c",
1,
{
"key": 1
}
],
"object": {
"key": {
"key": 1
}
}
}
关于转换我们有 3 种情况:
- 列表
- dicts(新对象)
- bool、int、float 和 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)
现在键值对是属性 - 对象。
输出:
John Smith
New York
123
1
1
将 JSON 粘贴为代码
支持TypeScript, Python, Ruby, C#, Java, Swift, Rust, Kotlin, C++, @9 @、JavaScript、Elm 和 JSON Schema。
- 从 JSON、JSON Schema 和 TypeScript 以交互方式生成类型和(反)序列化代码
- 将 JSON/JSON 架构/TypeScript 粘贴为代码
quicktype 从示例 JSON 数据推断类型,然后输出强类型模型和序列化程序,以便以所需的编程语言处理该数据。
输出:
# 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
此扩展程序在Visual Studio Code Marketplace 中免费提供。