1

I need to write one function which get json as input parameter and returns json.

Input json:

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

Output json:

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

LOOP the input array, process (some logic) and return the response with success and failed array items.

1
  • But {id:1} is not valid json, would have to be {"id":1} Commented Apr 20, 2018 at 7:24

2 Answers 2

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)

Prints:

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

Example at SQL Fiddle.

1
  • I want to process the input array (loop) and push the failed items into failed array in return json object. need to add new attribute (reason) with failed items like below. {"success":[{"id":2,"name":"b"}] "failed":[{"id":1,"name":"a","reason":"Conflict"}]} Commented Apr 20, 2018 at 7:47
0
    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

1
  • Its not javascript function. Postgresql function Commented Apr 20, 2018 at 8:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.