How to get a json object as column in postgresql?

后端 未结 2 802
忘了有多久
忘了有多久 2021-01-01 17:39

I have these table on mu PostgreSQL 9.05:

Table: core Fields: name, description, data

data f

相关标签:
2条回答
  • 2021-01-01 17:52

    As of PostgreSQL 9.4 you can also use json_to_record.

    Builds an arbitrary record from a JSON object (see note below). As with all functions returning record, the caller must explicitly define the structure of the record with an AS clause.

    For example:

    select * from json_to_record('{"a":1,"b":[1,2,3],"c":"bar"}') as x(a int, b text, d text)
    

    Returns

     a |    b    | d
    ---+---------+---
     1 | [1,2,3] |
    
    0 讨论(0)
  • 2021-01-01 18:10

    You can't do that "dynamically". You need to specify the columns you want to have:

    select name, description, id, 
           data ->> 'tax' as tax,
           data ->> 'other_attribute' as other_attribute
    from core;
    

    If you do that a lot, you might want to put that into a view.


    Another option is to create an object type in Postgres that represents the attributes in your JSON, e.g.

    create type core_type as (id integer, tax numeric, price numeric, code varchar);
    

    You can then cast the JSON to that type and the corresponding attributes from the JSON will automatically be converted to columns:

    With the above type and the following JSON: {"id": "100", "tax": "4.5", "price": "10", "code": "YXCV"} you can do:

    select id, (json_populate_record(null::core_type, data)).*
    from core;
    

    and it will return:

    id | tax  | price | code
    ---+------+-------+-----
     1 | 4.50 |    10 | YXCV
    

    But you need to make sure that every JSON value can be cast to the type of the corresponding object field.

    If you change the object type, any query using it will automatically be updated. So you can manage the columns you are interested in, through a central definition.

    0 讨论(0)
提交回复
热议问题