jQuery - Get value from JSON Stringify - javascript

I have a form, that I need to get the values from:
var formConfig = JSON.stringify($("#bookingform").serializeArray());
which returns below:
[{"name":"client_id","value":"1"},{"name":"consignee_id","value":""},{"name":"client","value":"DAKO"},{"name":"model","value":"2"},{"name":"type","value":"2"},{"name":"temperatur","value":"2"},{"name":"shipper_labels","value":"1"},{"name":"batteri_labels","value":"1"},{"name":"batteri_number","value":"2222"},{"name":"pickup","value":"April 27, 2017 18:25"},{"name":"intern_marks","value":"fdsfads"},{"name":"extern_marks","value":"sadsfdsf"},{"name":"consignee","value":""},{"name":"marks","value":""}]
I then need to access above values from the JSON string, which I am using this function to:
var confirmBooking = function(element, setting, correct, notcorrect) {
$('.confirm-booking')
.find(element)
.html(setting === 1 ? correct : notcorrect);
};
The thought is, I can use above function:
confirmBooking('.config_batteri', formConfig.client_id, "Yes", "No");
and so on..
formConfig.client_id should return 1, since that's the value in the JSON string above.
However it returns undefined:
console.log(formConfig.client_id); // Returns "undefined"

You need to use JSON.parse(), to make it a regular JavaScript object again.
What JSON.stringify() does is, as the name implies, make it a string. That is just a regular string, that represents JSON data. It doesn't magically have the JSON data properties.
Furthermore serializeArray() returns an array of {name: ..., value: ...} objects. If you didn't turn it into a JSON string, the result still could not easily be accessed by doing formConfig.client_id. You'd have to loop through the formConfig array, to find the desired name/value pair.
From the looks of it, you don't need to turn the JavaScript object into JSON at all, if you are just going to use it in the same script (unless you are going to send the JSON string somewhere else perhaps).
Based on OP's comments, I'm assuming OP just want to access a particular form element's value. Using jQuery, this can easily be accomplished with:
// get the value of the client_id element (assuming it's an input element)
var client_id = $( '#bookingform input[name="client_id"]' ).val();
// call the function
confirmBooking( '.config_batteri', client_id, "Yes", "No" );
If you want to have an object with all the form values, have a look at the answers in this question.

Do this:
var jsonStr = '[{"name":"client_id","value":"1"},
{"name":"consignee_id","value":""},
{"name":"client","value":"DAKO"},
{"name":"model","value":"2"},
{"name":"type","value":"2"},
{"name":"temperatur","value":"2"},
{"name":"shipper_labels","value":"1"},
{"name":"batteri_labels","value":"1"},
{"name":"batteri_number","value":"2222"},
{"name":"pickup","value":"April 27, 2017 18:25"},
{"name":"intern_marks","value":"fdsfads"},
{"name":"extern_marks","value":"sadsfdsf"},
{"name":"consignee","value":""},
{"name":"marks","value":""}]';
var obj = JSON.parse(jsonStr);
var val = obj[0].value;
The reason you can't do obj[0].name is because your parsed JSON object has a collection of objects, where the first object has this structure:
{
name:"client_id",
value:"1"
}
So, you have to access it using obj[0].value NOT obj[0].name as it would give you client_id.

I think that's what you want.
console.log(formConfig.confirmBooking);

would change of syntax help? please try
console.log(formConfig[0]['client_id']);
I hope it works for you

Since it's an array of objects, you target the first element which returns an object and then use the "value" property to get the actual value of 1 which you expected .
Also use parseInt("1") to get 1 as a type "number"
Hope this solves the issue ! Let me no ASAP
== EDIT
var formConfig = [{
"name": "client_id",
"value": "1"
}, {
"name": "consignee_id",
"value": ""
}, {
"name": "client",
"value": "DAKO"
}];
// This function returns the value for the name
function search(str) {
for (var obj of formConfig) {
if (obj.name == str) {
return obj.value;
}
}
}
search("client_id"); // 1
search("client"); // DAKO

Related

Passing a param to build a JSON object

How can I pass the subCategory in as an parameter for the function? I have a working solution just passing in the param and then having a switch do the work to make the JSON.subcategory read from the right place. However I feel like there is some thing I am missing on making this more functional, or OO friendly.
So is there a way to make the passed param understand its a variable and not the object literal.
json = {
weather: ["rain", "snow","sun"],
news: ["events", "local","world"]
}
messageBuilder(weather)
function messageBuilder(passedVariable){
var object = json.passedVariable;
// object = json.weather
console.log(JSON.stringify(object));
}
Also am I using the terms correctly? I tried to search google for an answer and ended up not really finding anything.
Just pass the object property key name (sub category) in as a string and use bracket notation to pick it from the data in the function.
Note: that's an object, not JSON, so I've named it as such in the example.
const obj = {
weather: ["rain", "snow", "sun"],
news: ["events", "local", "world"]
};
messageBuilder('weather');
function messageBuilder(subCat){
var object = obj[subCat];
console.log(JSON.stringify(object));
}
Just modify your code a little bit:
json = {
weather : [
"rain", "snow","sun"
],
news : [
"events", "local","world"
]
}
messageBuilder('weather');
function messageBuilder(passedVariable){
var object = json[passedVariable];
// object = json.weather
console.log(object);
}
First of all you should pass your parameter as a string. Then just pull out the property from the object using object['property']

JavaScript function which accesses Object field

I'm looking for a JavaScript function which receives in parameter the field of the object we'd like to have and returns its value :
var object = {
field1 : "test1",
field2 : [
"test2", "test3"
]
};
var getField = function (field){
return object[field];
}
getField("field1"); // working
getField("field2[0]"); // not working due to the array
Am I obliged to split the parameter by "[" to get the correct field ?
To get the correct array item you need to use:
getField("field2")[0] // prints "test2"
When using getField("field2[0]"), you're accessing from object a property with the name "field2[0]", which doesn't exist and will return undefined.
Check more details about the property accessors.

form.serializeArray() converts each element into string

Trying to form.serializeArray() and passing serialized data to the server.
Problem: This method also converts boolean and integer to string. And on server side on the basis of the
value , I am trying to get the data type because of which it gives me String everytime.
Actual Output:
[Object { name="para1", value="1"}, Object { name="para2", value="2"}, Object { name="para3", value="true"}, Object { name="para4", value="rep1"}]
Required Output:
[Object { name="para1", value=1}, Object { name="para2", value=2}, Object { name="para3", value=true}, Object { name="para4", value="rep1"}]
Please suggest the solution for this.
You could process the value string of each object and create a new array with converted values. For example, the strings true and false would be converted to their respective boolean value and numbers would be converted to integers. Note that my example below is quite simple and doesn't cover all possibilities (floats are also converted to integers).
Edit: As noted by #sanfor in the comments, every string containing an integer is converted to an integer value, although strings like "123" could also be treated as strings. However, given the information in the question that the type of the input is unknown, this method provides the desired results.
JSFiddle (open the console to see the output):
var values = [
{
name: 'para1',
value: '1'
},
{
name: 'para2',
value: 'true'
},
{
name: 'para3',
value: 'this is a string'
}
];
var result = values.map(function(obj) {
var value;
if (obj.value === 'true') {
value = true;
} else if (obj.value === 'false') {
value = false;
} else if (!isNaN(obj.value)) {
value = parseInt(obj.value);
} else {
value = obj.value;
}
return {
name: obj.name,
value: value
};
});
console.log(result);
As #Vohuman already mentioned, the values are strings as intended. To make them something else you would need to either use some other function to achieve it, or handle the output of the serializeArray afterwards.
More likely solution is to teach your back-end to resolve the type based on the field. You usually know what you are expecting on back-end so you also know the type required and based on that you can (try) to cast it to be correct type.

Get values from object if the name of the object is stored as a variable?

I have a JSON object return with the following format:
"miscObject": {
"205": [
{
"h": "Foo",
"l": "Bar"
}
]
}
miscObject contains somewhere over 1500 entries, each named incrementally.
How can I get to the values of 'miscObject.205.h' and 'miscObject.205.l' if I have "205" stored in variable without having to loop through all of the objects inside miscObject?
It seems that you're talking about Javascript objects rather than a JSON string.
x[y] and x.y are mostly interchangeable when accessing properties of Javascript objects, with the distinction that y in the former may be an expression.
Take advantage of this to solve your problem, like so:
var num = '205';
console.log(miscObject[num].l);
// ^^^^^
// \
// instead of `.num`, which wouldn't be the same as
// `num` is not the literal name of the property
Use the member lookup syntax
var miscObject = $.parseJSON(theJsonString);
var name = '205';
miscObject[name].h;
Object values can be accessed 2 ways--using the 'dot' notation as you mentioned, or by using []'s:
The following should work:
var result = miscObject["205"].h;
var miscObject = JSON.parse(your-JSON-object);
var value = miscObject['205'].h
You can do this to get the object:
num = '205'
miscObject[num]

Key value pairs using JSON

Is there a way to handle data structures using JSON object in a way of Key/ Value pairs?
If so can some one elaborate how to access associated value object from the key
Assume that I have something like this
KEY1 | VALUE OBJECT1 - (NAME: "XXXXXX", VALUE:100.0)
KEY2 | VALUE OBJECT2 - (NAME: "YYYYYYY", VALUE:200.0)
KEY3 | VALUE OBJECT3 - (NAME: "ZZZZZZZ", VALUE:500.0)
A "JSON object" is actually an oxymoron. JSON is a text format describing an object, not an actual object, so data can either be in the form of JSON, or deserialised into an object.
The JSON for that would look like this:
{"KEY1":{"NAME":"XXXXXX","VALUE":100},"KEY2":{"NAME":"YYYYYYY","VALUE":200},"KEY3":{"NAME":"ZZZZZZZ","VALUE":500}}
Once you have parsed the JSON into a Javascript object (called data in the code below), you can for example access the object for KEY2 and it's properties like this:
var obj = data.KEY2;
alert(obj.NAME);
alert(obj.VALUE);
If you have the key as a string, you can use index notation:
var key = 'KEY3';
var obj = data[key];
var object = {
key1 : {
name : 'xxxxxx',
value : '100.0'
},
key2 : {
name : 'yyyyyyy',
value : '200.0'
},
key3 : {
name : 'zzzzzz',
value : '500.0'
},
}
If thats how your object looks and you want to loop each name and value then I would try and do something like.
$.each(object,function(key,innerjson){
/*
key would be key1,key2,key3
innerjson would be the name and value **
*/
//Alerts and logging of the variable.
console.log(innerjson); //should show you the value
alert(innerjson.name); //Should say xxxxxx,yyyyyy,zzzzzzz
});
JSON (= JavaScript Object Notation), is a lightweight and fast mechanism to convert Javascript objects into a string and vice versa.
Since Javascripts objects consists of key/value pairs its very easy to use and access JSON that way.
So if we have an object:
var myObj = {
foo: 'bar',
base: 'ball',
deep: {
java: 'script'
}
};
We can convert that into a string by calling window.JSON.stringify(myObj); with the result of "{"foo":"bar","base":"ball","deep":{"java":"script"}}".
The other way around, we would call window.JSON.parse("a json string like the above");.
JSON.parse() returns a javascript object/array on success.
alert(myObj.deep.java); // 'script'
window.JSON is not natively available in all browser. Some "older" browser need a little javascript plugin which offers the above mentioned functionality. Check http://www.json.org for further information.
I see what you are trying to ask and I think this is the simplest answer to what you are looking for, given you might not know how many key pairs your are being sent.
Simple Key Pair JSON structure
var data = {
'XXXXXX' : '100.0',
'YYYYYYY' : '200.0',
'ZZZZZZZ' : '500.0',
}
Usage JavaScript code to access the key pairs
for (var key in data)
{ if (!data.hasOwnProperty(key))
{ continue; }
console.log(key + ' -> ' + data[key]);
};
Console output should look like this
XXXXXX -> 100.0
YYYYYYY -> 200.0
ZZZZZZZ -> 500.0
Here is a JSFiddle to show how it works.

Categories