简体   繁体   中英

How can I parsing JSON with Node.js in electron renderer.js file?

I'd like to parse JSON formatted dataset from a web server(edit in Electron renderer.js file)

 refresh.addEventListener("click", function(){ const http = require('http'); http.get( 'http://teamparamount.cn:8080/Paramount/filesroot?username=test', (resp) =>{ let data = ''; // A chunk of data has been recieved. resp.on('data', (chunk) =>{ data += chunk; }); // The whole response has been received. Print out the result. resp.on('end', () =>{ // console.log(JSON.parse(data).info); // var obj = JSON.stringify(data); var hhh = JSON.parse(data); var xxx = JSON.parse(data).info; // alert(typeof obj); // console.log(hhh.length); // console.log(obj); console.log(data); console.log(hhh.status); console.log(hhh.info); console.log(hhh.info[1].time); console.log(hhh.info.length); console.log(hhh.info[408]); // console.log(obj.info[1]); // console.log(obj.status); // console.log(obj.status.length); function getJsonLth(obj){ var index = 0; for(var i=0;i<obj.length;i++){ if (obj[i] == ':') { index++; } return index; // alert(json1.abc[i].name); } }; console.log(getJsonLth(xxx)); }); }).on("error", (err) => { console.log("Error: " + err.message); }); }); 
In the red circle part, the first output is JSON format dataset which server sent. The second output is the result after using JSON.parse(data).status . The third output is the result after using JSON.parse(data).info. And I think var xxx = JSON.parse(data).info xxx is an array as it's showed in the third output. However, what I wanna do is to get the size, time, type, url these value separately in each element in the array. But, as you can see, the output of console.log(hhh.info[1].time); is undefined. Also, I wanna get this array's length, and I just use console.log(hhh.info.length) and the result is 409 and I am confused about it. This result clarify it is a string not an array. And I'd like to get these value and the length of the array at the same time. What should I do? Many thanks.

http://teamparamount.cn:8080/Paramount/filesroot?username=test returns this:

{"status":"success","info":"[{\"size\":\"10105\"...

where info property is a string, which has to be parsed separately. That's what you apparently trying to do in:

var xxx = JSON.parse(data).info;

But instead of JSON.parse(data).info you should do: JSON.parse(data.info) . Then you will receive your info array into the xxx variable.

it's because the info object is a stringify object, so you need to parse it and override it, and after you will be able to read the entire data object.

var info = JSON.parse(data.info);
data.info = info;

I hope it will help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM