27

I am trying to create a json object from variables that I am getting in a form.

var firstName = $('#firstName').val();
var lastName  = $('#lastName').val();
var phone     = $('#phoneNumber').val();
var address   = $('#address').val();

So far I have the code below but it will not validate or work. Im new to this, please help! Changing var to this:

var jsonObject = 
                {
                 firstName: firstName, 
                 lastName: lastName,
                 phoneNumber:phoneNumber,
                 address:address
                }

in JSONlint i am getting this error:

Parse error on line 1: varjsonObject={
^ Expecting '{', '['

Vel
  • 9,027
  • 6
  • 34
  • 66
Anthony
  • 2,330
  • 8
  • 44
  • 64
  • Are you sure you want to create **JSON** and not rather a JS object? Also, what parts of the object are supposed to be variables? How is the first part connected to the second part? If you really want to convert `formObject` to JSON, then you are out of luck, since you cannot convert jQuery objects to JSON (and you are missing `$` in `"firstName": ('#firstName')`). Please be specific about the result you want to get, right now it's a bit confusing since it seems you are struggling with the right terminology. – Felix Kling Oct 19 '12 at 17:26
  • You might find it helpful to read more about object in the MDN JavaScript Guide: https://developer.mozilla.org/en-US/docs/JavaScript/Guide/Working_with_Objects. – Felix Kling Oct 19 '12 at 17:33
  • the result I want is a json object that i can send using ajax. – Anthony Oct 19 '12 at 18:05
  • 2
    JSON objects don't exist (http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/). Either you want actually a JS object and set it as `data: ...` in the `$.ajax` configuration. Or you want to convert the object to JSON and send a string containing JSON to the server. The reason why you get the error in JSONlint is that you are inputting JavaScript (`var jsonObject = ..`), and not JSON. If you input the output of `JSON.stringify(jsonObject)` instead, it will probably validate. I really recommend you to take the time to learn what exactly JSON is, compared to JS object literals. – Felix Kling Oct 19 '12 at 18:23
  • `var jsonObject = {...}` is valid JavaScript, ***but not valid JSON***! – Salman A Dec 10 '12 at 20:39

5 Answers5

29

if you need double quoted JSON use JSON.stringify( object)

var $items = $('#firstName, #lastName,#phoneNumber,#address ')
var obj = {}
$items.each(function() {
    obj[this.id] = $(this).val();
})

var json= JSON.stringify( obj);

DEMO: http://jsfiddle.net/vANKa/1

charlietfl
  • 170,828
  • 13
  • 121
  • 150
14

It's called on Object Literal

I'm not sure what you want your structure to be, but according to what you have above, where you put the values in variables try this.

var formObject =  {"formObject": [
                {"firstName": firstName, "lastName": lastName},
                {"phoneNumber": phone},
                {"address": address},
                ]}

Although this seems to make more sense (Why do you have an array in the above literal?):

var formObject = {
   firstName: firstName
   ...
}
hvgotcodes
  • 118,147
  • 33
  • 203
  • 236
6

Try this to see how you can create a object from strings.

var firstName = "xx";
var lastName  = "xy";
var phone     = "xz";
var adress    = "x1";
var obj = {"firstName":firstName, "lastName":lastName, "phone":phone, "address":adress};
console.log(obj);
4

You're referencing a DOM element when doing something like $('#lastName'). That's an element with id attribute "lastName". Why do that? You want to reference the value stored in a local variable, completely unrelated. Try this (assuming the assignment to formObject is in the same scope as the variable declarations) -

var formObject = {
    formObject: [
        {
            firstName:firstName,  // no need to quote variable names
            lastName:lastName
        },
        {
            phoneNumber:phoneNumber,
            address:address
        }
    ]
};

This seems very odd though: you're creating an object "formObject" that contains a member called "formObject" that contains an array of objects.

Madbreaks
  • 19,094
  • 7
  • 58
  • 72
2
var formValues = {
    firstName: $('#firstName').val(),
    lastName: $('#lastName').val(),
    phone: $('#phoneNumber').val(),
    address: $('#address').val()
};

Note this will contain the values of the elements at the point in time the object literal was interpreted, not when the properties of the object are accessed. You'd need to write a getter for that.

jbabey
  • 45,965
  • 12
  • 71
  • 94
  • Thanks for the tip. Is the way i used variables correct in my updated code? – Anthony Oct 19 '12 at 18:07
  • @Anthony Yes, it is correct. However, JSLint will provide you with no meaningful information because you have a **javascript object**, not JSON. – jbabey Oct 19 '12 at 18:28