I converted below JSON using https://json2csharp.com/code-converters/json-to-python to a dataclass:
{
"bypassCd": [
"Duis sint ipsum in",
"consequat"
]
}
It generaged below dataclass – for some reason, it is showing error at .from_dict() method and I’m unable to figure it out. Please advise
from typing import List
from typing import Any
from dataclasses import dataclass
import json
@dataclass
class Root:
bypassCd: List[str]
@staticmethod
def from_dict(obj: Any) -> 'Root':
_bypassCd = [.from_dict(y) for y in obj.get("bypassCd")]
return Root(_bypassCd)
# Example Usage
jsonstring = json.loads('''
{
"bypassCd": [
"Duis sint ipsum in",
"consequat"
] }
''')
root = Root.from_dict(jsonstring)
print(root)
error:
File "/local_home/afxx1285/pyprograms/test2.py", line 11
_bypassCd = [.from_dict(y) for y in obj.get("bypassCd")]
^
SyntaxError: invalid syntax
2
Answers
You are getting a
SyntaxError
on this line:… because you are trying to run the method/function
from_dict
, but you haven’t written which object holds this function. You could specify an object like this before the function call:I think what you want to do is recursively call the
Root.from_dict
function, so you should probably write:This still throws an error since your algorithm needs some changes, but this answers your initial question.
This is what I came up with, but it’s hard to say if it fits your needs. I can’t understand why it’s trying some recursion calling
from_dict
from insidefrom_dict
.