I am trying to decode JSON into python objects. Looked at some of the samples/answers here and other website but can't seem to find the answer.
Here's the code:
import json
class A:
def __init__ (self, n, a):
self.n = n
self.a = a
class B:
def __init__ (self, b, listOfA):
self.b = b
self.listOfA = []
for a in listOfA:
self.listOfA.append(a)
class ADecoder(json.JSONDecoder):
def decode (self, json_string):
default_obj = super(A, self).decode(json_string)
a_obj = A(default_obj['n'], default_obj['a'])
return a_obj
class BDecoder(json.JSONDecoder):
def decode (self, json_string):
default_obj = super(BDecoder, self).decode(json_string)
#The problem with the code above is that here listOfA is a list of
#generic python objects.
b_obj = B(default_obj['b'], [default_obj['listOfA']])
return b_obj
Here's sample JSON
{
"b": "b",
"listOfA": [
{
"a": "a1",
"n": "n1"
},
{
"a": "a2",
"n": "n2"
}
],
}
I also tried to see if I can re-convert the listOfA back to string and then calling ADecoder. For example something like this:
aDecoder = ADecoder()
b_obj = B(default_obj['b'], [aDecoder.decode(x.__str__()) for x in default_obj['servers']])
Firstly this didn't work because Python doesn't know how to convert my object to (JSON) string but even if it did the above that would be terribly inefficient.
Any suggestions on how I could solve the problem? Is there a way to inject my ADecoder before Python converts the JSON string to generic objects? Tried looking at the samples, tutorials, etc., can't seem to find this scenario.