1

I use the json library to decode json text

import json

I have a Party class defined like this:

class Party(object):
    id = ""
    code = ""
    create_date = ""
    citizenship = ""

an object_hook method:

def as_party(d):
    p = Party()
    p.__dict__.update(d)
    return p

I can use this method in order to get a Party object from a json text:

def parse_as(s, typo_class):
    return json.loads(str(s), object_hook=typo_class)

When I call the parse_as method on a json text containing encoded Party class, i get an object of type Party.

json_text = {'id': 2, 'code': '2', 'create_date': null, 'citizenship': null}
party1 = parse_as(json_text, as_party)

I can call its attributes like this:

print party1.code

My problem is to make the parse_as method able to parse a json text containing a list of Party objects like this one:

json_text = [{'id': 2, 'code': '2', 'create_date': null, 'citizenship': null}, {'id': 5, 'code': '3', 'create_date': null, 'citizenship': null}, {'id': 6, 'code': '8', 'create_date': null, 'citizenship': null}]

Please help me and thanks in advance!

2 Answers 2

2

object hook needs to be changed

def as_party(d):
    if isinstance(d, dict):
      p = Party()
      p.__dict__.update(d)
    elif isinstance(d, list):
     out = []
     for i in d:
       n = Party()
       n.__dict__.update(i)
       out.append(n)
     p = out
    else:
      raise Exception('got non-dict value %s' % d)
    return p

btw, i wouldnt use __dict__, would rather use setattr with some prefix...

because if key value is a python keyword, that wont be good.

>>> a = Foo()
>>> a.__dict__['except'] = 1
>>> a.except
  File "<stdin>", line 1
    a.except
           ^
SyntaxError: invalid syntax
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you for the solution :) Can you explain your other alternative (using setattr) ?
1

as for different approach using setattr and avoiding colision of python keywords you can use:

def as_party(d):
    if isinstance(d, dict):
      p = Party()
      for k,v in d.iteritems():
        setattr(p, 'v_%s' % k, v) # you can assign any prefix you want
    elif isinstance(d, list):
     out = []
     for i in d:
       n = Party()
       for k,v in i.iteritems():
         setattr(n, 'v_%s' % k, v)
       out.append(n)
     p = out
    else:
      raise Exception('got non-dict value %s' % d)
    return p

but then you would have to access those values with prefix that we incorporated like so:

print party.v_for, party.v_except # etc..

generally, you could work out the code that it does not allow python keywords:

import keyword

def as_party(d):
    if isinstance(d, dict):
      p = Party()
      for k,v in d.iteritems():
        if keyword.iskeyword(k):
          raise Exception('Cannot accept %s as a property name. That is resrved python keyword' % k)
        setattr(p, k, v) # you can assign any prefix you want
    elif isinstance(d, list):
     out = []
     for i in d:
       n = Party()
       for k,v in i.iteritems():
        if keyword.iskeyword(k):
          raise Exception('Cannot accept %s as a property name. That is resrved python keyword' % k)
         setattr(n, k, v)
       out.append(n)
     p = out
    else:
      raise Exception('got non-dict value %s' % d)
    return p

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.