How to create a json object with input variable - javascript

I want to create a JSON object with input variable. I have a 2 input field. when I click button i want to take input values and make a JSON object with that value. I cannot create a JSON object with entered value.
I try that
//getting the value of input as a variable
let id=document.querySelector("#id");
let title=document.querySelector("#title");
first I try the below. it sends a blank value instead of variable string
var vObj= '{"id":'+id.value+',"title":'+title.value+'}'
I also try that to
var vObj = {"id":{},"v_title":{}, "v_category":{}};
vObj.id=id.value;
vObj.title=title.value;
tried that
let asd=id.value;
let bsd=title.value;
var vObj = {id:asd, title:bsd}
it returns a blank value instead of variable value.
i am making a mistake that the trigger button has typo. i couldn't see that. sorry

You can create an object with name proeprties and then use JSON.stringify to turn this into valid JSON:
//let id = document.querySelector("#id").value;
let id = 'my_id';
//let title = document.querySelector("#title").value;
let title = 'my_title';
console.log('ID: ' + id);
console.log('Title: ' + title);
var vObj = { id: id, title: title };
var json = JSON.stringify(vObj);
console.log(json);
This line:
var vObj = { id: id, title: title };
Creates an object with an id with the value of the id variable, and a title with the value of the title variable.
This line:
var json = JSON.stringify(vObj);
Converts the object vObj to a JSON string.
Output:
ID: my_id
Title: my_title
{"id":"my_id","title":"my_title"}
Edit followimg #FelixKling comment
In ES6 it is possible to simplify the declaration of vObj using:
var vObj = {id, title};
This will create the same object with the assumed property names id and title. Obviously if your variable is not named id or title this will not work.

First create an object, then stringify it to JSON.
var jsonObj = JSON.stringify( { "id" : id, "title" : title } );

Related

Changing properties in JSON data

how can I change the "ABC" field in the code below?
var data = {ABC:{key:'dynamic_key',value:'dynamic_value'}}
Normally, I can give the value I want by saying data.ABC.key, but what I really want is to go as data.CCC instead of data.ABC, so I just want to change the ABC name.
Re-assign the inner object to the new outer object key, then delete the previous.
var data = {ABC:{key:'dynamic_key',value:'dynamic_value'}}
data.CCC = {...data.ABC}
delete data.ABC
console.log(data)
That also could be (without using delete)
var data = {ABC:{key:'dynamic_key',value:'dynamic_value'}}
data = {CCC: data.ABC}
console.log(data)
EDIT... It you want to use a string from a variable to set the new key, use the bracket notation:
var data = {ABC:{key:'dynamic_key',value:'dynamic_value'}}
var newKey="CAR"
data[newKey] = data.ABC
delete data.ABC
console.log(data)
data.CCC = data.ABC // on object create new key name. Assign old value to this
delete data.ABC //delete object with old key name
output:
{
"CCC":
{
"key": "dynamic_key",
"value": "dynamic_value"
}
}

How to store JSON object as option value in select tag?

I am trying to append JSON object to a select tag for future reference by using below code
$.each(actualData, function (key, value) {
var valueToAppend = [];
var vehicleId = value._id['$oid'];
var availableSeats = value.NumberOfSeats;
var item = {};
item["VehicleId"] = vehicleId;
item["AvailableSeats"] = availableSeats;
valueToAppend.push(item);
$('#vehicle_'+guid).append($('<option>', {value: '' + valueToAppend + '', text: '' + value.VehicleNumber + ''}));
});
It is appending values in browser like "value="[object Object]".
I want it should append like {VehicleId:"36ae8c855677879c88", AvailableSeats: "60"}. I want it should store id and number of seats. Please help!!!
You can store an object as a value of HTML element. So you have to store json string as a value
$('#vehicle_'+guid).append($('<option>', {value: '{VehicleId:' + valueToAppend.item.VehicleId+',AvailableSeats:'+valueToAppend.item.AvailableSeats+ '}', text:value.VehicleNumber}));
Try this . I am converting your Object to JSON String
$('#vehicle_'+guid)
.append($("<option></option>")
.attr("value",JSON.stringify(valueToAppend))
.text(value.VehicleNumber));

How do I programmatically build an object from my form data that includes arrays

I need to display some values on a jsp page, grab input from user and send it back to a controller that is using Jackson to bind it to my backing data object. Several rows that I display on the screen are backed by an array and are created with <c:forEach> and I'm generating a path like "blobs[0].id" and "blobs[0].text". When I try to put them into the json object to be sent back to the controller by an ajax call, they aren't being added to the object properly. The property name ends up having "[0]" in the name instead of representing the object at that array index.
<script>
var formData = {};
formData.blobs = [];
formData.blobs[0] = {};
formData.blobs[0].id = "English";
formData.blobs[0].text = "Hello";
formData["blobs[1].id"] = "German";
formData["blobs[1].text"] = "Guten Tag";
console.log(formData);
</script>
ends up looking like {blobs: [0 : {id: "English", text: "Hello"}], blobs[1].id: "German", blobs[1].text: "Guten Tag"} instead of
{blobs: [0 : {id: "English", text: "Hello"}, 1 : {id: "German", text: "Guten Tag"}]}
I am trying to assemble the model thusly:
<script>
function createModel() {
var form = $("#theForm");
var formData = {};
$.each(form, function(i, v){
var input = $(v);
if (input.attr("name")) {
formData[input.attr("name")] = input.val();
}
});
}
</script>
Accessing obj["attr"] is an option to access an object's attribute, so obj["attr[1][22]"] will access an attribute called "attr[1][22]", while accessing obj["attr"][1][22] will access the second element of obj.attr, and the second element's 22th element as well..
The solution will be to access formData["blobs"][0].id or even formData["blobs"][0]["id"]
you can format the string to your needs
$('#yourform').serializeArray() returns an array:
[
{"name":"foo","value":"1"},
{"name":"bar","value":"xxx"},
{"name":"this","value":"hi"}
]
$('#yourform').serialize() returns a string:
"foo=1&bar=xxx&this=hi"
so, in your case
var formData = {};
formData.blobs = [];
$('#yourform').serializeArray().forEach(function(blob){
formData.blobs.push({
id: blob.name,
text: blob.value
});
})

JavascriptSerializer.Deserialize & Encoding

I use Vietnamese in input content to an textbox like "ngày 1".
The first time I do Javascript.Serialize an object & put it in array, store in cookie:
class sampleCookie
{
public string tripDate;
}
=>I got right value string is "ngày 1".
Again, I add new record to this list with another string "ngày 2".
=> I got the first record value string is "ngà y 1"
I can't figure out the way to Encoding for it.
What I'm missing?
This's my code
var estCookie = Request.Cookies[inputModel.SampleCookieName];
if (estCookie != null)
{
var serializer = new JavaScriptSerializer();
var serializeModel = serializer.Deserialize<ListSampleCookie>(estCookie.Value);
// I Update string value in here
//Put insert item to list
serializeModel.Add(new SampleCookie
{
TripDate = inputModel.TripDate ,
Memo = inputModel.Memo,
OptionFee = inputModel.OptionFee
});
// Serialize data
var sampleData = serializer.Serialize(serializeModel);
//Update cookie value
estCookie.Value = sampleData;
Response.AppendCookie(estCookie);
}

extract single variable from JSON array

I hope my question is not as stupid as I think it is...
I want to extract (the value of) a single variable from an JSONarray. I have this jquery code
$(document).ready(function(){
$("#gb_form").submit(function(e){
e.preventDefault();
$.post("guestbook1.php",$("#gb_form").serialize(),function(data){
if(data !== false) {
var entry = data;
$('.entries').prepend(entry);
}
});
});
});
the content of data looks like this ("MyMessage" and "MyName" are values written in a simple form from user):
[{"message":"MyMessage","name":"MyName"}]
the var "entry" should give (more or less) following output at the end:
"Send from -MyName- : -MyMessage-"
I'm not able to extract the single array values from data. I tried things like that:
var message = data['message'];
var name = data['name']
var entry = "Send from" + name + ":" +message;
but that gives "Send from undefined: undefined"
Hope you can help me with that.
you can do like this to get first item of array:
var msg = "Send from"+data[0].name + " "+data[0].message;
console.log(msg );
SAMPLE FIDDLE
UPDATE:
as you are using $.post you will need to explicitly parse response as json:
$.post("guestbook1.php",$("#gb_form").serialize(),function(data){
var response = jQuery.parseJSON(data);
var msg = "Send from"+response [0].name + " "+response [0].message;
console.log(msg );
});
To access an array you use the [] notation
To access an object you use the . notation
So in case of [{JSON_OBJECT}, {JSON_OBJECT}]
if we have the above array of JSON objects in a variable called data, you will first need to access a particular Json Object in the array:
data[0] // First JSON Object in array
data[1] // Second JSON Object in array.. and so on
Then to access the properties of the JSON Object we need to do it like so:
data[0].name // Will return the value of the `name` property from the first JSON Object inside the data array
data[1].name // Will return the value of the `name` property from the second JSON Object inside the data array

Categories

Resources