How to convert neomodel object into json? (is not JSON serializable)

1.8k views Asked by At

I use Falcon framework and neomodel in order to communicate with neo4j database.

I have some nodes in DB and I try to return information about them via API (get methon) as a JSON object.

In order to retrive information I use the code people = Person.nodes I iterate throu people:

for p in people:
    print(p)

and I get:

{'name': 'John', 'id': 0, 'uid': '584d9b0517584b8194f222052bf177ff'}
{'name': 'Paul', 'id': 1, 'uid': 'f5763c01704e449885f846e87e1fcb6d'}

When I do json.dumps() on single entity I get an error:

TypeError: <Person: {'name': 'John', 'id': 0, 'uid': '584d9b0517584b8194f222052bf177ff'}> is not JSON serializable

How can I convert neomodel object into json object?

3

There are 3 answers

0
StefanE On

A bit of an old question but this is how I work with this..

Creating a function on the class so I can control what data to return. With __properies__ instead of the .to_json funtion you will get all properties.

class Player(StructuredNode):
  mid = IntegerProperty(unique_index=True)
  f_name = StringProperty()
  l_name = StringProperty()
  email = StringProperty()
  team = RelationshipFrom('Team', 'PLAYER', model=PlayerRel)

  def to_json(self):
    return {
        "id": self.mid,
        "firstName": self.f_name,
        "lastName": self.l_name,
        "email": self.email,
        "fullName": self.f_name + ' ' + self.l_name
    }

Then I have a node with has several Players connected and I just do this to return an array of players that can be serialized:

...
team = Team.nodes.get(team_id=id)
return ([player.to_json() for player in team.players])
0
luinstra On

Using json.dumps(p.__properties__) does the trick. Using p.__dict__ tries to encode the neomodel property classes, which will throw an error.

0
v100ev On

It seems like every p in your people is an object. Try something like json.dumps(p.__dict__). If it's a common neomodel node object then this should work.