Leeran Setton
Leeran Setton

Reputation: 315

Can't access JSON value from curl

I use this curl command:

curl -X POST -H "Content-Type: application/json" http://localhost:8081/creditcard -d '{"credit-card":"1234-5678-9101-1121"}'

In my js file, I have this code block to get the credit-card's value:

request.on('data', function(data) {
    var cc = 'credit-card';

    var a = JSON.parse(data.toString());

    console.log(a[cc]);
}

For this I get:

undefined:1
'{credit-card:1234-5678-9101-1121}'
^
SyntaxError: Unexpected token '
    at Object.parse (native)
    at IncomingMessage.<anonymous> (<path>\ccserver.js:32:34)
    at IncomingMessage.emit (events.js:107:17)
    at IncomingMessage.Readable.read (_stream_readable.js:373:10)
    at flow (_stream_readable.js:750:26)
    at resume_ (_stream_readable.js:730:3)
    at _stream_readable.js:717:7
    at process._tickCallback (node.js:355:11)

So I tried to use JSON.stringify as followed:

request.on('data', function(data) {
    var cc = 'credit-card';

    var a = JSON.parse(JSON.stringify(data.toString()));

    console.log(a[cc]);
}

But this is what I get:

undefined
undefined

However, when I try to parse a hard-coded json string, it goes ok:

var jsonString = '{"credit-card":"1234-5678-9101-1121"}';
var a = JSON.parse(jsonString);
console.log(a[cc]);

Result:

1234-5678-9101-1121

What is the correct way to do get the data out of this json?

Please advise Thanks

Upvotes: 2

Views: 785

Answers (1)

Sheetal Mohan Sharma
Sheetal Mohan Sharma

Reputation: 2924

Try reading from absolute path

curl -X POST
     -H 'Content-Type:application/json'
     -H 'Accept: application/json'
     --data-binary @/full/path/to/test.json
     http://server:port/xyz/abc/blah -v -s

Well, you already have String so all you need to convert it to javascript variable and get using .notation. Suggest to use firebug to see what is in variable.

 obj = JSON.parse(json);
 obj.cc or obj.cc[0] 

should give you what you want.

Upvotes: 1

Related Questions