Skip to main content

Add jsonb type to CubicWeb

Project description

Add a new attribue type to CubicWeb: Jsonb. This type is mapped to the jsonb PostgreSQL data type.

Declaration

In your schemas, you can use the new type as follow:

>>> class MyEntityType(EntityType):
...     json_attribute = Jsonb(required=True)
...

Get/Set

To provide a value for a Jsonb attribute, you can use either:

  • a dict,
  • a JSON string.

For example, you can write the following code:

>>> my_entity.cw_set(json_attribute={'a': [1, 2, 3]})

The code below wil have exactly the same effect:

>>> my_entity.cw_set(json_attribute=u'{"a": [1, 2, 3]}')

Please note that, whatever way you set the value (string or dict), you will always get back a dict when asking for it:

>>> my_entity.json_attribute
{u'a': [1, 2, 3]}

Querying

In RQL, you can query a Jsonb attribute in multiple ways. For example, you can ask for attributes containing a specific key/value pair:

>>> import json
>>> rql('Any X WHERE X json_attribute J HAVING JSONB_CONTAINS(J, %(json_value)s)=True',
        {'json_value': json.dumps({u'a': 1})})

You can ask for existence of a specific key:

>>> rql('Any X WHERE X json_attribute J HAVING JSONB_EXISTS(J, %(key)s)=True',
        {'key': u'b'})

You can get the value for a key:

>>> rql('Any JSONB_GET(J, %(key)s) WHERE X json_attribute J, X eid %(eid)s',
        {'key': u'a', 'eid': 1234})

Note: JSONB_GET() will always return a string. If the value is a JSON object (or a JSON array), you may want to use json.loads() afterwards to have a dict (or a list).

One final remark: as the PostgreSQL documentation suggests, you should use the same structure for your JSON data in the same column. This makes querying much easier.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Files for cubicweb-jsonb, version 0.2.0
Filename, size File type Python version Upload date Hashes
Filename, size cubicweb_jsonb-0.2.0-py3-none-any.whl (7.4 kB) File type Wheel Python version py3 Upload date Hashes View
Filename, size cubicweb-jsonb-0.2.0.tar.gz (8.5 kB) File type Source Python version None Upload date Hashes View

Supported by

AWS AWS Cloud computing Datadog Datadog Monitoring DigiCert DigiCert EV certificate Facebook / Instagram Facebook / Instagram PSF Sponsor Fastly Fastly CDN Google Google Object Storage and Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Salesforce Salesforce PSF Sponsor Sentry Sentry Error logging StatusPage StatusPage Status page