将JSON解码为python对象

将JSON解码为python对象,python,json,deserialization,Python,Json,Deserialization,我是python新手,在将JSON解码到python类时遇到了问题。例如: 如果我们有一个代表人物的python类: Class Person: def __init__(self, Fname, Lname, Age): self.FirstName = Fname self.LastName = Lname self.Age = Age 现在我有了一个JSON,比如说,我从一个web服务主体或其他什么地方得到了它,它是这样的: Jso

我是python新手,在将JSON解码到python类时遇到了问题。例如:

如果我们有一个代表人物的python类:

Class Person:
    def __init__(self, Fname, Lname, Age):
        self.FirstName = Fname
        self.LastName = Lname
        self.Age = Age
现在我有了一个JSON,比如说,我从一个web服务主体或其他什么地方得到了它,它是这样的:

JsonOBJ = {"FirstName":"Mostafa","LastName":"Mohamed","Age":"26"}
我需要解码JSON,使Person类型的对象充满值,并访问其属性,如:

Obj.FirstName

谢谢。

如果您已经将JSON字符串作为Python字典,您只需使用**扩展它:

如果不知道,另一个选项是创建一个类方法,该类方法知道如何从JSON字符串创建Person对象。通过这种方式,可以从调用代码中封装创建逻辑:

class Person:
    def __init__(self, Fname, Lname, Age):
        self.FirstName = Fname
        self.LastName = Lname
        self.Age = Age

    @classmethod
    def from_json_string(cls, json_string):
        dict_obj = json.loads(json_string)
        return cls(**dict_obj)

p = Person.from_json_string('{"Fname": "a", "Lname": "b", "Age": 11}')

print(p.FirstName)
# a

请记住,我展示的两种方法都是使用**将字典扩展到Person的单个参数。这意味着键必须与_uinit__;期望的参数匹配。如果没有,则需要将正确的键/值传递给uu init_uu,而不是使用**。

是否有需要完整类实现的原因?如果您只是希望通过键而不是使用dict来访问属性,那么可以创建namedtuple

from collections import namedtuple

def dict_to_namedtuple(d):
    # This sets up a namedtuple called 'Person' with the provided keys
    # It then creates the namedtuple with the unpacked dict
    return namedtuple('Person', d.keys())(**d)

d = {"FirstName":"Mostafa","LastName":"Mohamed","Age":"26"}
person = dict_to_named_tuple(d)

print(person)
# Person(FirstName='Mostafa', LastName='Mohamed', Age='26')

print(person.FirstName)
# 'Mostafa'

谢谢工作得很好,我只需要首先将JSON字符串转换为字典。谢谢你,伙计
from collections import namedtuple

def dict_to_namedtuple(d):
    # This sets up a namedtuple called 'Person' with the provided keys
    # It then creates the namedtuple with the unpacked dict
    return namedtuple('Person', d.keys())(**d)

d = {"FirstName":"Mostafa","LastName":"Mohamed","Age":"26"}
person = dict_to_named_tuple(d)

print(person)
# Person(FirstName='Mostafa', LastName='Mohamed', Age='26')

print(person.FirstName)
# 'Mostafa'