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.
Related
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
I have a JSON object formatted like {"Foo": ["B","A","R"]}
I am trying to access the values of the array like this:
var json = '{"Foo": ["B","A","R"]}';
expression = JSON.Parse(json, function(key, value){
if(key == "Foo"){
console.log(value.length); // logs "3"
console.log(value[1]); // logs "undefined"
}
});
If I ask for the length of value it returns the correct length of the array, but if I ask for the value it returns undefined and I am not quite sure why.There are other values in the JSON that I am able to access just fine, but they are not arrays. Any insight would be appreciated. Thanks!
You should use JSON.parse like this:
var json = '{"Foo":["B","A","R"]}';
var object = JSON.parse(json);
// object is now and object containing the data from 'json'
var expression = object["Foo"][1]; // object["Foo"] refers to the
// value with key "Foo"
(Calling JSON.parse with a callback parameter is an advanced feature for transforming the JSON object, not reading it. In almost all cases, though, you want to use it like the above code, with no callbacks.)
As mentioned in another answer, if you simply want to retrieve the second element of Foo, you can do that easily enough after parsing using standard property access techniques such as obj.Foo[1].
Assuming you really want to use the optional second "reviver" parameter to JSON.parse, you need to return the value from the "reviver" callback;
expression = JSON.Parse(json, function(key, value){
if (key == "Foo"){
console.log(value[1]);
}
return value;
^^^^^^^^^^^^^
});
The reason it appears you can't access value[1] but you can access value.length is (as mentioned by user663031) you don't have a return value.
The reviver function replaces one value with another, if no return is specified all functions will return undefined. The order the reviver receives the values is: first each of the values in the array separately, then the array.
In your code each value has already been replaced with "undefined", so the array has three undefined values as reported by the length. value[1] really is returning the value at position 1 but it is set to "undefined".
When the json string has arrays the reviver function is called with index, [Object] as key, value parameters .
This sniped of code that filter object properties on parse phase will be helpful:
var json = '{"_embedded": [{"a":"A","b":"B","links": {"c":"C"}},{"a":"A2", "b":"B2","links": {"c":"C2"}}]}';
var schemaNames=["_embedded", "a"];
var result= JSON.parse(json, function(k, v) {
console.log(k,v);
if ("" === k){
return v;
}
// On arrays k is a number
else if (schemaNames.indexOf(k) > -1 || !isNaN(k)){
return v;
}
});
console.log(JSON.stringify(result));
Output: {"_embedded":[{"a":"A"},{"a":"A2"}]}
https://jsfiddle.net/pdorgambide/vphbmtk1/
use this code
var json = {'foo' : ['B', 'A', 'R']};
$.each(json, function(key, value){if(key == 'foo'){console.log(value[1]);}});
you already have a json object so no need to parse it again.
I was trying the following code :
function doSomething(field, value) {
var someObj = { field : value };
console.log("The object looks like : %j, someObj);
}
I call it like doSomething('emailid', 'a#b.com');
The output was {field : 'a#b.com'}.
How can i make field to take the value from the function call?
Would like to get these values : {'emailid', 'a#b.com'}
Thanks for your time.
When you define an object with the object literal syntax you can either speciy the name of the key as you did, like {field: value} or you can use string literals to define the key such as {"field": value}. Unfortunately there is no way to substitute a variable for a key with object literal syntax, but there is a way to accomplish your outcome.
function doSomething(key, value) {
var someObj = {};
someObj[key.toString()] = value;
return someObj;
}
That should perform your task.
I have a Javascipt object which I use as dictionary
var obj={
xxx:'1'
yyy:'2'
}
However -
xxx and yyy should be a jQuery object.
something like :
var obj =
{
$('#div1'):'1' ,
$('#div2'):'2'
}
is it possible ?
also, How can I get the "value" for key $('#div2') ?
p.s.
I the $.data cant help me here since its also a key value
and i need in the key - object Type also.
Object keys can only be strings ( or Symbol), period. See Member Operators - Property Names # MDN.
Choose a reasonable string representation, and use that. In this case, I'd say the selector string looks like a decent choice:
{
'#div1': '1',
'#div2': '2'
}
also, How can I get the "value" for key $('#div2') ?
Use one of the member operators, either dot notation
var obj = { /* stuff */ };
var value = obj.propertyName;
console.log(value);
or bracket notation (more useful for property names not known until runtime):
var value = obj['propertyName'];
Use a WeakMap which works like a dictionary where the key can be anything. Note that you cannot list all the keys of the map
const aMap = new WeakMap;
const anObject = {};
aMap.set(Number, "It's the Number class")
aMap.set(anObject, "It's an object")
console.log(aMap.get(Number)) // It's the Number class
console.log(aMap.get(anObject)) // It's an object
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]