Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

creating json object with variables

Tags:

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 '{', '['

like image 224
Anthony Avatar asked Oct 19 '12 17:10

Anthony


People also ask

Can you set variables in JSON?

The data in the file data. json has been loaded into a JSONObject named jsonData. Using data. json as your guide, create String variables named name, publisher, and language and set them to the appropriate values from data.

Can we create object in JSON?

JSON cannot be an object. JSON is a string format. The data is only JSON when it is in a string format.

How do I create a JSON object dynamically in node JS?

To create JSON object dynamically via JavaScript, we can create the object we want. Then we call JSON. stringify to convert the object into a JSON string. let sitePersonnel = {}; let employees = []; sitePersonnel.


2 Answers

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

like image 135
charlietfl Avatar answered Oct 31 '22 08:10

charlietfl


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    ... } 
like image 27
hvgotcodes Avatar answered Oct 31 '22 06:10

hvgotcodes