Nodejs 的 JSON.parse 問題
发布于 2年前 作者 hkmung 1450 次浏览

JSON.parse 解析json 上有問題嗎 ??

代碼 : var old_m, new_m, oldArr, newArr;

console.log(“TEST A”);

old_m = '[{"date":"20-06 11:23:01","_id":"51c2759fa828f0920b000005"}]'; oldArr = JSON.parse( old_m );

new_m = '{"date":"20-06 11:23:01","_id":"51c2759fa828f0920b000005"}’; newArr = JSON.parse( new_m );

console.log(“old_text:” + old_m ); console.log(“old Arr:” + oldArr.date );

console.log(“new_text:” + new_m ); console.log(“new Arr:” + newArr.date );

console.log(“TEST B”);

old_m = '[{"date":"20-06 11:23:01","_id":"51c2759fa828f0920b000005"},{"date":"20-06 11:23:01","_id":"51c2759fa828f0920b000005"}]'; oldArr = JSON.parse( old_m );

new_m = '{"date":"20-06 11:23:01","_id":"51c2759fa828f0920b000005"},{"date":"20-06 11:23:01","_id":"51c2759fa828f0920b000005"}’; newArr = JSON.parse( new_m );

console.log(“old_text:” + old_m ); console.log(“old Arr:” + oldArr.date );

console.log(“new_text:” + new_m ); console.log(“new Arr:” + newArr.date );

============================== OUTPUT :

TEST A

old_text:[{"date":"20-06 11:23:01","_id":"51c2759fa828f0920b000005"}] old Arr:undefined

new_text:{"date":"20-06 11:23:01","_id":"51c2759fa828f0920b000005"} new Arr:20-06 11:23:01

TEST B

old_text:[{"date":"20-06 11:23:01","_id":"51c2759fa828f0920b000005"},{"date":"20-06 11:23:01","_id":"51c2759fa828f0920b000005"}] old Arr:undefined

new_text:{"date":"20-06 11:23:01","_id":"51c2759fa828f0920b000005"},{"date":"20-06 11:23:01","_id":"51c2759fa828f0920b000005"} new Arr: 已死

4 回复

你要搞清楚json后是对象还是数组,要是数组就[]括起来,要是对象就用对象定义。

[{"date":"20-06 11:23:01","_id":"51c2759fa828f0920b000005"},{"date":"20-06 11:23:01","_id":"51c2759fa828f0920b000005"}] old Arr:undefined

即是數組用 oldArr.length , 再 for loop 吧

这代码看起来好乱

哦 , test 代碼没有寫得很好 , 見諒 因為我習慣了 php print_r display 所有 array

Nodejs 的做法應該是

var text = '[{"date":"20-06 11:23:01","_id":"51c2759fa828f0920b000005"}]'; var arr = JSON.parse( text );

console.log(“Date:” + arr[0].date );

回到顶部