0

所以我正在使用 Python 中的一些 JSON 数据。它基本上是一个 API 的包装器,虽然我想对我的值进行点访问data.size,但我已经做了一些研究,但我找不到想要的结果。

json.loads用来解析我的数据,所以我尝试了对象挂钩,但这不是我想要的。

这是我要复制的示例 Go 代码。

type dat struct {
    ResponseTime int
    Body body
}

type body struct {
    Day int
    Month int
    Year int
}

var h dat
// e here is my json
data = json.Unmarshal(e, &h)

我在 Python 中的结果相似,但它们是同一类的实例。我的目标是能够解析嵌套的字典,并且我希望能够定义哪个字典分配给哪个对象……不确定你是否理解,但有适合你的 Go 代码。

4

3 回答 3

0

使用dataclassdacite

from dataclasses import dataclass
import dacite

@dataclass
class Body:
    day:int
    month:int
    year:int

@dataclass
class Dat:
    response_time: int
    body: Body
data = {'response_time':12, 'body':{'day':1,'month':2,'year':3}}

dat: Dat = dacite.from_dict(Dat,data)
print(dat)

输出

Dat(response_time=12, body=Body(day=1, month=2, year=3))
于 2021-10-02T09:12:49.023 回答
0

使用 pymarshaler(接近 golang 方法)

import json

from pymarshaler.marshal import Marshal


class Body:
    def __init__(self, day: int, month: int, year: int):
        self.day = day
        self.month = month
        self.year = year

class Dat:
    def __init__(self, response_time: int, body: Body):
        self.response_time = response_time
        self.body = body

marshal = Marshal()

dat_test = Dat(3, Body(1, 2, 3))
dat_json = marshal.marshal(dat_test)
print(dat_json)

result = marshal.unmarshal(Dat, json.loads(dat_json))
print(result.response_time)

https://pythonawesome.com/marshall-python-objects-to-and-from-json/

于 2021-10-02T09:25:29.047 回答
-1

所以事实证明这并不难,我只是不想尝试。对于任何有同样问题的人,这里是代码。

class Typs(object):
    def __init__(self):
        self.type = int
        self.breed = str


class Deets(object):
    def __init__(self):
        self.color = str
        self.type = Typs()


class Base(object):
    def __init__(self):
        self.name = str
        self.details = Deets()


d = {
    "name": "Hello",
    "details": {"color": "black", "type": {"type": 2, "breed": "Normal"}},
}

h = Base()


def unmarshal(d, o):
    for k, v in d.items():
        if hasattr(o, k):
            if isinstance(v, dict):
                unmarshal(v, getattr(o, k))
            else:
                setattr(o, k, v)

    return o


x = unmarshal(d, h)
于 2021-10-02T09:06:06.683 回答