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); 
6
  • 1
    JSON.stringify does not create an object, but a string from an object.
    – Bergi
    CommentedDec 5, 2012 at 20:22
  • Maybe you should be using JSON.parse, as you seem to have them confused ?
    – adeneo
    CommentedDec 5, 2012 at 20:23
  • @adeneo where would i use JSON.parse?
    – s_p
    CommentedDec 5, 2012 at 20:24
  • 1
    $('#myForm').serializeObject() already returns object.CommentedDec 5, 2012 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
    CommentedDec 5, 2012 at 20:27

1 Answer 1

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); 

    Start asking to get answers

    Find the answer to your question by asking.

    Ask question

    Explore related questions

    See similar questions with these tags.