I want to create a JSON string from a javascript for loop. This is what I tried to do (which gives me something that looks like a JSON string), but it does not work.
var edited = "";
for(var i=1;i<POST.length-1;i++) {
edited += '"'+POST[i].name+'":"'+POST[i].value+'",';
}
It gives me this:
"type":"empty","name":"email-address","realname":"Email Address","status":"empty","min":"empty","max":"empty","dependson":"empty",
This does not work if I try to convert it into a JSON object later.
Two problems:
{and end with}.,which may be recognized as invalid.It’s probably better to use a library, but to correct your code:
var edited = "";tovar edited = "{";to start your JSON string with a{edited = edited.slice(0, -1);after the for loop to remove the trailing comma.edited += "}";after the previous statement to end your JSON string with a}Your final code would be:
Again, it’s best to use a library (e.g.
JSON.stringify) by making an object with a for loop, adding properties by usingPOST[i].nameas a key andPOST[i].valueas the value, then using the library to convert the object to JSON.Also, you are starting with index
1and ending with indexPOST.length-2, therefore excluding indices0(the first value) andPOST.length-1(the last value). Is that what you really want?