Parsing JSON fields in PostgreSql and parsing JSON fields in TEXT

Initialization operation

Create table

CREATE TABLE orders (  "ID" int8 NOT NULL,
                       "info_j" json NOT NULL,
                       "info_t" text NOT NULL
);

initialization table

INSERT INTO orders("ID", "info_j","info_t") VALUES (1, '{
    
    "name":"张三","items":{
    
    "product":"啤酒","qty":6}}','{
    
    "name":"张三","items":{
    
    "product":"啤酒","qty":6}}');
INSERT INTO orders("ID", "info_j","info_t") VALUES (2, '{
    
    "name":"李四","items":{
    
    "product":"辣条","qty":8}}','{
    
    "name":"李四","items":{
    
    "product":"辣条","qty":8}}');
INSERT INTO orders("ID", "info_j","info_t") VALUES (3, '{
    
    "name":"王五","items":{
    
    "product":"苹果","qty":18}}','{
    
    "name":"王五","items":{
    
    "product":"苹果","qty":18}}');
INSERT INTO orders("ID", "info_j","info_t") VALUES (4, '{
    
    "name":"赵一","items":{
    
    "product":"香蕉","qty":20}}','{
    
    "name":"赵一","items":{
    
    "product":"香蕉","qty":20}}');

lookup table
Insert image description here

Parse JSON fields

The query uses the -> operator to query all customers in json as keys

SELECT info_j -> 'name' AS customer FROM orders;

Insert image description here
The ->> operation is used below to obtain all customer names as values

SELECT info_j ->> 'name' AS customer FROM orders;

Insert image description here
Query the value based on the key of the json object

SELECT info_j -> 'items' ->> 'product' AS customer FROM orders;

Insert image description here

Parse JSON fields in TEXT

In fact, just like parsing JSON fields, we only need to add::json
Insert image description here
Insert image description here
Insert image description here

Guess you like

Origin blog.csdn.net/qq_46548855/article/details/134310921