解析转义的javascript

时间:2018-03-13 06:12:10

标签: javascript json

我有以下字符串,我试图解析为JSON对象,然后变成一个javascript数组:

"[{\"items\":\"nut\",\"sales\":6,\"prices\":10},\n {\"items\":\"bolt\",\"sales\":8,\"prices\":20},\n {\"items\":\"cam\",\"sales\":0,\"prices\":15},\n {\"items\":\"cog\",\"sales\":3,\"prices\":20}]"

我删除了换行符来获取

"{\"items\":\"nut\",\"sales\":6,\"prices\":10}, {\"items\":\"bolt\",\"sales\":8,\"prices\":20}, {\"items\":\"cam\",\"sales\":0,\"prices\":15}, {\"items\":\"cog\",\"sales\":3,\"prices\":20}"

我试过这个

   dd = "[{\"items\":\"nut\",\"sales\":6,\"prices\":10},\n {\"items\":\"bolt\",\"sales\":8,\"prices\":20},\n {\"items\":\"cam\",\"sales\":0,\"prices\":15},\n {\"items\":\"cog\",\"sales\":3,\"prices\":20}]";
   dd = dd.replace(/\\n/g, '');
   dd = dd.replace(/[\[\]']+/g,'');
   console.log(JSON.parse(dd));
   dd= JSON.parse(dd));

但是由于dd.items为null

,这实际上并没有因为某种原因解析json

4 个答案:

答案 0 :(得分:3)

  

但是由于dd.items的原因,这实际上并没有解析json   空

无需从字符串中删除换行符\n,只需直接执行JSON.parse



var dd = JSON.parse( "[{\"items\":\"nut\",\"sales\":6,\"prices\":10},\n {\"items\":\"bolt\",\"sales\":8,\"prices\":20},\n {\"items\":\"cam\",\"sales\":0,\"prices\":15},\n {\"items\":\"cog\",\"sales\":3,\"prices\":20}]" );
console.log(dd);




此外,dd是一个数组,因此您需要迭代dd才能获得items

dd.forEach( s => console.log(s.items) );

答案 1 :(得分:0)

let x = "[{\"items\":\"nut\",\"sales\":6,\"prices\":10},\n {\"items\":\"bolt\",\"sales\":8,\"prices\":20},\n {\"items\":\"cam\",\"sales\":0,\"prices\":15},\n {\"items\":\"cog\",\"sales\":3,\"prices\":20}]";
let y = x.substr(1, x.length - 2).split(',\n').map(JSON.parse);
console.log(y);

答案 2 :(得分:0)

使用    JSON.parse(dd); 功能删除此

答案 3 :(得分:0)



var data="[{\"items\":\"nut\",\"sales\":6,\"prices\":10},\n {\"items\":\"bolt\",\"sales\":8,\"prices\":20},\n {\"items\":\"cam\",\"sales\":0,\"prices\":15},\n {\"items\":\"cog\",\"sales\":3,\"prices\":20}]";

//use JSON parse that will convert the string to JSON like array of objects please dont do any modification in the returned string

console.log(JSON.parse(data));