1

I have a form and would like to append the contents of it to an existing array.
I am using JSON.stringify( $('#myForm').serializeObject() ) to convert my form elements into json objects.
The form has user info that i would like to append into myArr then append this list into an existing array.

myArr is populating fine, its just appending that into existingJsonArray i seem to be having problems with.

I saw this but since JSON.stringify creates the full json array would i need to knock out the [{ and }] ?

Is this the correct approach?

var existingJsonArray = [];
var myArr = [];

myArr.unshift( JSON.stringify( $('#myForm').serializeObject() ) );

existingJsonArray.unshift(myArr);
Community
  • 1
  • 1
t q
  • 4,593
  • 8
  • 56
  • 91
  • 1
    `JSON.stringify` does not create an object, but a string from an object. – Bergi Dec 05 '12 at 20:22
  • Maybe you should be using JSON.parse, as you seem to have them confused ? – adeneo Dec 05 '12 at 20:23
  • @adeneo where would i use `JSON.parse`? – t q Dec 05 '12 at 20:24
  • 1
    `$('#myForm').serializeObject() ` already returns object. – Shiplu Mokaddim Dec 05 '12 at 20:25
  • 2
    JSON is a *string* format. It is a *string representation* of a data structure. There is no such thing as a "JSON object" or a "JSON array". – gen_Eric Dec 05 '12 at 20:27
  • @tq - who knows, you're just saying three times that you are creating an object with JSON.stringify, which of course stringifies an object to JSON format, and JSON.parse would be the opposite, and actual create an object from a string, but you're mixin jQuery methods that already does this for you, so it's a bit uneccessary. – adeneo Dec 05 '12 at 20:28

1 Answers1

3

Please notice that JSON is the string representation of objects - and not suited well for manipulating them.

var array = [], // an Array literal in JavaScript code
    formObject;
formObject = $('#myForm').serializeObject(); // an object representing the form
array.unshift([formObject]); // not sure why you need the nested array
// create string containing JSON representation of the array:
var jsonString = JSON.stringify(array);
Bergi
  • 630,263
  • 148
  • 957
  • 1,375