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
CodePudding user response:
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 inside from_dict
.
from typing import Mapping, List
from dataclasses import dataclass
import json
@dataclass
class Root:
bypassCd: List[str]
@staticmethod
def from_dict(obj: Mapping) -> 'Root':
_bypassCd = obj.get("bypassCd", [])
return Root(_bypassCd)
# Example Usage
my_dict = json.loads('''
{
"bypassCd": [
"Duis sint ipsum in",
"consequat"
]
}
''')
root = Root.from_dict(my_dict)
print(root)
CodePudding user response:
You are getting a SyntaxError
on this line:
_bypassCd = [.from_dict(y) for y in obj.get("bypassCd")]
... 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:
obj.from_dict(y)
I think what you want to do is recursively call the Root.from_dict
function, so you should probably write:
Root.from_dict(y)
This still throws an error since your algorithm needs some changes, but this answers your initial question.