Search code examples
pythonjsoncurlstdin

cURL : Sending part data from stdin in POST


I've to make 2 cURLs. The data from 1 curl needs to be formatted & sent as an input in the 2nd cURL. I've attempted the following:

curl -XPOST -H "Content-type: application/json" -d '{"a":1, "b" : 2}' 'https://a.com/a' | python -c "import json,sys;o=json.load(sys.stdin);o1=dict(id=o['foo'],hash=o['bar']);print(json.dumps(o));print(json.dumps(o1));" | curl -XPOST -H "Content-type: application/json" https://a.com/b -d @-

In the above combination of cURLs, I'm parsing the data received from 1st cURL via python and then print both the received output & the parsed output on stdin, then take the input from stdin as the data for 2nd cURL.

Problem: There are two JSONs which are being printed in stdin and all of that is being passed as data in 2nd cURL. How can I select just the last line from stdin which is the actual data that should be passed in the 2nd cURL?


Solution

  • A possible approach suggested by armnotstrong helped me in getting it right. Though this is, technically, not an answer to the question but it is a good workaround.

    I'm printing my outputs, which are not required to send to the 2nd cURL, in error stream. Following is the working cURL:

    curl -XPOST -H "Content-type: application/json" -d '{"a":1, "b" : 2}' 'https://a.com/a' | \
    python -c "import json,sys;o=json.load(sys.stdin);o1=dict(id=o['foo'],hash=o['bar']);sys.stderr.write(json.dumps(o));print(json.dumps(o1));" |\
    curl -XPOST -H "Content-type: application/json" https://a.com/b -d @-