如何用JSON数据中的数据填充类中的对象?

2024-09-30 05:14:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我想用从JSON接收的数据填充我的对象

JSON中的数据键与我的类中的参数命名相同

有没有有效的方法来创建填充对象?因此,我的类将有超过50个变量

我的测试课程:

class Joint:
    spineX = 0.0
    spineY = 0.0
    spineZ = 0.0

Json数据:

print(jsonData) #prints -> {"spineX":8.9,"spineY":7.7,"spineZ":9.9}

Tags: 数据对象方法json参数命名class课程
2条回答

好吧,我要附加这个答案,因为你说的是class attributes,而不是instance attributes。您可以使用built-in functionsetattr

This is the counterpart of getattr(). The arguments are an object, a string and an arbitrary value. The string may name an existing attribute or a new attribute. The function assigns the value to the attribute, provided the object allows it. For example, setattr(x, 'foobar', 123) is equivalent to x.foobar = 123.

您可以这样做:

class Joint:
    spineX = 0.0
    spineY = 0.0
    spineZ = 0.0

s = '{"spineX":8.9,"spineY":7.7,"spineZ":9.9}'
o = json.loads(s)

for k in o.keys():
    setattr(Joint, k, o[k])

print(Joint.spineX)
print(Joint.spineY)
print(Joint.spineZ)

输出:

8.9
7.7
9.9

现在,Joint的每个新实例都将具有这些class attribute值。如果您这样做:

x = Joint()
print(x.spineX)
print(x.spineY)
print(x.spineZ)

您还将获得:

8.9
7.7
9.9

更有趣的是,使用setattr()甚至可以添加尚未定义的class attributes。例如:

setattr(Joint, "spineA", 10.0)
print(Joint.spineA)

输出

10.0

也许可以在类中添加__init__

import json


class Joint:
    def __init__(self, spineX, spineY, spineZ):
        self.spineX = spineX
        self.spineY = spineY
        self.spineZ = spineZ


s = '{"spineX":8.9,"spineY":7.7,"spineZ":9.9}'
o = json.loads(s)
joint = Joint(**o)

print(vars(joint))

相关问题 更多 >

    热门问题