【问题标题】:Postgresql function - Parse the input json, build and return json objectPostgresql 函数 - 解析输入 json,构建并返回 json 对象
【发布时间】:2018-09-30 20:22:36
【问题描述】:

我需要编写一个函数来获取json作为输入参数并返回json。

输入json:

[{"id":1,"name":"a"},{"id":2,"name":"b"}]

输出json:

{  "success":[{"id":1,"name":"a"}],"failed":[{"id":2,"name":"b"}]}

循环输入数组,处理(一些逻辑)并返回包含成功和失败数组项的响应。

【问题讨论】:

  • 但是{id:1} 不是有效的json,必须是{"id":1}

标签: arrays json postgresql function postgresql-9.4


【解决方案1】:
select  json_build_object(
            'success', json_agg(col1) filter (where col1->>'name' <> 'a'),
            'failure', json_agg(col1)  filter (where col1->>'name' = 'a'))
from    json_array_elements('[{"id":1,"name":"a"},{"id":2,"name":"b"}]'::json) as t(col1)

打印:

{"success" : [{"id":2,"name":"b"}], "failure" : [{"id":1,"name":"a"}]}

Example at SQL Fiddle.

【讨论】:

  • 我想处理输入数组(循环)并将失败的项目推送到失败的数组中以返回 json 对象。需要添加带有失败项目的新属性(原因),如下所示。 {"成功":[{"id":2,"name":"b"}] "失败":[{"id":1,"name":"a","re​​ason":"冲突"} ]}
【解决方案2】:
    console.clear();
    var jsonObj = '[{"id":1,"name":"a"},{"id":2,"name":"b"}]';

    function formatJson(input) {

        let arr = JSON.parse(jsonObj);
        //     console.log(arr);
        let retJson = {
            "success": [],
            "failure": []
        };

        arr.forEach((item) => {

            if (true) { // some condition to put json data in success object. Here i am making it always true for implementation purpose
                retJson.success.push(item);

            } else {
                //failure logic
            }

        });

        return retJson;

    }
    var formattedJSONOutput = formatJson(jsonObj);
    console.log(formattedJSONOutput);

JsFiddle Link

【讨论】:

  • 它不是javascript函数。 Postgresql 函数
猜你喜欢
  • 1970-01-01
  • 2014-11-22
  • 1970-01-01
  • 2018-07-14
  • 2012-11-02
  • 1970-01-01
  • 1970-01-01
  • 2021-07-15
  • 1970-01-01
相关资源
最近更新 更多