How do I convert a json file to a python class?

2024/11/11 1:19:03

Consider this json file named h.json I want to convert this into a python dataclass.

{"acc1":{"email":"[email protected]","password":"acc1","name":"ACC1","salary":1},"acc2":{"email":"[email protected]","password":"acc2","name":"ACC2","salary":2}}

I could use an alternative constructor for getting each account, for example:

import json
from dataclasses import dataclass@dataclass
class Account(object):email:strpassword:strname:strsalary:int@classmethoddef from_json(cls, json_key):file = json.load(open("h.json"))return cls(**file[json_key])

but this is limited to what arguments (email, name, etc.) were defined in the dataclass.

What if I were to modify the json to include another thing, say age? The script would end up returning a TypeError, specifically TypeError: __init__() got an unexpected keyword argument 'age'.

Is there a way to dynamically adjust the class attributes based on the keys of the dict (json object), so that I don't have to add attributes each time I add a new key to the json?

Answer

Since it sounds like your data might be expected to be dynamic and you want the freedom to add more fields in the JSON object without reflecting the same changes in the model, I'd also suggest to check out typing.TypedDict instead a dataclass.

Here's an example with TypedDict, which should work in Python 3.7+. Since TypedDict was introduced in 3.8, I've instead imported it from typing_extensions so it's compatible with 3.7 code.

from __future__ import annotationsimport json
from io import StringIO
from typing_extensions import TypedDictclass Account(TypedDict):email: strpassword: strname: strsalary: intjson_data = StringIO("""{"acc1":{"email":"[email protected]","password":"acc1","name":"ACC1","salary":1},"acc2":{"email":"[email protected]","password":"acc2","name":"ACC2","salary":2,"someRandomKey": "string"}
}
""")data = json.load(json_data)
name_to_account: dict[str, Account] = dataacct = name_to_account['acc2']# Your IDE should be able to offer auto-complete suggestions within the
# brackets, when you start typing or press 'Ctrl + Space' for example.
print(acct['someRandomKey'])

If you are set on using dataclasses to model your data, I'd suggest checking out a JSON serialization library like the dataclass-wizard (disclaimer: I am the creator) which should handle extraneous fields in the JSON data as mentioned, as well as a nested dataclass model if you find your data becoming more complex.

It also has a handy tool that you can use to generate a dataclass schema from JSON data, which can be useful for instance if you want to update your model class whenever you add new fields in the JSON file as mentioned.

https://en.xdnf.cn/q/72085.html

Related Q&A

PyTorch how to compute second order Jacobian?

I have a neural network thats computing a vector quantity u. Id like to compute first and second-order jacobians with respect to the input x, a single element. Would anybody know how to do that in PyTo…

Tensorflow setup on RStudio/ R | CentOS

For the last 5 days, I am trying to make Keras/Tensorflow packages work in R. I am using RStudio for installation and have used conda, miniconda, virtualenv but it crashes each time in the end. Install…

Cant import soundfile

Im using Anaconda and Im trying to import soundfile/pysoundfile. I installed the package by running conda install -c conda-forge pysoundfile and I think it succeeded because when I run conda list it sh…

Most efficient way to multiply a small matrix with a scalar in numpy

I have a program whose main performance bottleneck involves multiplying matrices which have one dimension of size 1 and another large dimension, e.g. 1000: large_dimension = 1000a = np.random.random((1…

MultiValueDictKeyError / request.POST

I think I hav a problem at request.POST[title]MultiValueDictKeyError at /blog/add/post/"title"Request Method: GETRequest URL: http://119.81.247.69:8000/blog/add/post/Django Version: 1.8.…

How can I auto run py.test once a relative command has been change?

Via autonose or nosy, it will automatically run the nosetests once the some tests file or the relative files have been changes. I would like to ask that whether py.test provides the similar function fo…

Publish a post using XML-RPC WordPress API and Python with category

Im doing a migration from a website to another one which use Wordpress. I created new custom types for my needs (with the plugin Custom Post Types), and I created categories for each custom type.I then…

Django registration email not sending

Ive been trying to get the django-registration-redux account activation email to send to newly registered users.Ive gotten all non-email related parts to work, such as loggin in/out and actually regist…

NumPy data type comparison

I was playing with comparing data types of two different arrays to pick one that is suitable for combining the two. I was happy to discover that I could perform comparison operations, but in the proces…

A simple method for rotating images in reportlab

How can we easily rotate an image using reportlab? I have not found an easy method. The only way found comes from http://dods.ipsl.jussieu.fr/orchidee/SANORCHIDEE/TEMP/TEMP_LOCAL/cdat_portable/lib_new…