How do I query using fields inside the new PostgreSQL JSON datatype?

后端 未结 3 1762
我寻月下人不归
我寻月下人不归 2020-11-22 11:43

I am looking for some docs and/or examples for the new JSON functions in PostgreSQL 9.2.

Specifically, given a series of JSON records:

[
  {name: \"         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-22 12:38

    With postgres 9.3 use -> for object access. 4 example

    seed.rb

    se = SmartElement.new
    se.data = 
    {
        params:
        [
            {
                type: 1,
                code: 1,
                value: 2012,
                description: 'year of producction'
            },
            {
                type: 1,
                code: 2,
                value: 30,
                description: 'length'
            }
        ]
    }
    
    se.save
    

    rails c

    SELECT data->'params'->0 as data FROM smart_elements;
    

    returns

                                     data
    ----------------------------------------------------------------------
     {"type":1,"code":1,"value":2012,"description":"year of producction"}
    (1 row)
    

    You can continue nesting

    SELECT data->'params'->0->'type' as data FROM smart_elements;
    

    return

     data
    ------
     1
    (1 row)
    

提交回复
热议问题