我使用这个curl命令:
curl -X POST -H "Content-Type: application/json" http://localhost:8081/creditcard -d '{"credit-card":"1234-5678-9101-1121"}'在我的js文件中,我有这个代码块来获取信用卡的值:
request.on('data', function(data) {
var cc = 'credit-card';
var a = JSON.parse(data.toString());
console.log(a[cc]);
}为此,我得到了:
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)因此,我尝试使用JSON.stringify,如下所示:
request.on('data', function(data) {
var cc = 'credit-card';
var a = JSON.parse(JSON.stringify(data.toString()));
console.log(a[cc]);
}但我得到的是:
undefined
undefined然而,当我尝试解析一个硬编码的json字符串时,它运行正常:
var jsonString = '{"credit-card":"1234-5678-9101-1121"}';
var a = JSON.parse(jsonString);
console.log(a[cc]);结果:
1234-5678-9101-1121从这个json中获取数据的正确方法是什么?
请告知,谢谢
发布于 2015-06-05 22:36:21
尝试从绝对路径读取
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你已经有了字符串,所以你所需要做的就是把它转换成javascript变量,然后使用.notation来获取。建议使用firebug来查看变量中的内容。
obj = JSON.parse(json);
obj.cc or obj.cc[0] 应该能给你想要的。
https://stackoverflow.com/questions/30669151
复制相似问题