Two problems:
- You want an object, so the JSON string has to start with
{
and end with }
.
- There is a trailing
,
which may be recognized as invalid.
It's probably better to use a library, but to correct your code:
- Change
var edited = "";
to var edited = "{";
to start your JSON string with a {
- Add
edited = edited.slice(0, -1);
after the for loop to remove the trailing comma.
- Add
edited += "}";
after the previous statement to end your JSON string with a }
Your final code would be:
var edited = "{";
for(var i=1;i<POST.length-1;i++) {
edited += '"'+POST[i].name+'":"'+POST[i].value+'",';
}
edited = edited.slice(0, -1);
edited += "}";
Again, it's best to use a library (e.g. JSON.stringify
) by making an object with a for loop, adding properties by using POST[i].name
as a key and POST[i].value
as the value, then using the library to convert the object to JSON.
Also, you are starting with index 1
and ending with index POST.length-2
, therefore excluding indices 0
(the first value) and POST.length-1
(the last value). Is that what you really want?