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 '{', '['
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.
JSON cannot be an object. JSON is a string format. The data is only JSON when it is in a string format.
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.
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
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 ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With