I have a JSON data set that’s being deserialized and written into a textarea input in the form:
{
"key1": "",
"key2": "0",
"key3": "",
"key4": "0"
}
Using the following for loop:
for (var key in jsonObj.myData) {
textarea.value += key + ": " + jsonObj.myData[key] + "n";
}
The text appears correctly in the textarea after this operation. Later, I serialize this data using the following for loop:
console.log(textarea.value); // Shows text with line breaks as expected
for (var line in textarea.value.split("n")) {
console.log(line); // Shows only incrementing number
var keyval = line.split(": ");
json += """ + keyval[0] + "": "" + (keyval[1] || "") + "",";
}
This results in serialized data which looks like this:
{
"0": "",
"1": "",
"2": "",
"3": ""
}
I would expect that splitting on "n" would return an array of "key: value" strings as they were entered into the textarea, not (I assume) the index of the line. What am I doing wrong?
2
Answers
Serializing js objects can be done in much simplier way.
Use
JSON.stringify(<object>)
to turn objects into JSON strings.Use
JSON.parse(<string>)
to turn JSON strings into objects.for-in
loop is iterating over the keys of the array, which are indices, returned bytextarea.value.split("n")
, not over the elements themselves.