Founding a values in parsed multidimensional array in javascript - javascript

I've got this data serialized by JSON to string:
var json = '[{"data":{"id":2,"gid":3,"name":"Travis","surname":"Stewart","skin":0}},{"data":{"id":3,"gid":3,"name":"Ziutek","surname":"Stewart","skin":0}}]';
And now im going to parse this back to object, like:
var charData = JSON.parse(json);
How can i get data from this for each datas?
for(var char in charData.data) {
console.log(char.id);
}
This wasn't work... Any other solutions?

Okay. Got it! Here's the code how can i get this:
var json = '[{"data":{"id":2,"gid":3,"name":"Travis","surname":"Stewart","skin":0}},{"data":{"id":3,"gid":3,"name":"Ziutek","surname":"Stewart","skin":0}}]';
var charData = JSON.parse(json);
for(var char in charData) {
console.log(charData[char].data.name);
}
Thanks a lot for all! :) SOLVED.

you have more then one Data object , so you need to do a forOf To your chardata not to charData.data :
for(var char in charData) {
console.log(charData[char].data.id);
console.log(charData[char].data.name);
....
}

Related

How to get json value by string?

I receive the following string from the server response:
var jsonData = '[{"firstName":"Bill","lastName":"Gates"},{"firstName":"George","lastName":"Bush"},{"firstName":"Thomas","lastName":"Carter"}]';
I see some jquery plugins can predefine the keys they want
like: index:"firstName", and they get a ul like
<li>Bill</li>
<li>George</li>
<li>Thomas</li>
If index:"lastName", they get a ul like
<li>Gates</li>
<li>Bush</li>
<li>Carter</li>
The only way I know how to parse a json format string is:
var object = JSON.parse(jsonData);
var firstName = object[i].firstName;
var lastName= object[i].lastName;
The plugin pass the index like a parameter
function f(index) {
return object[i].index;
}
How can they achieve this?
Thanks for helping!
You can access object properties with square brackets. JS objects work like arrays in this regard.
var objects = JSON.parse(jsonData),
key = "firstName";
objects.forEach(function (obj) {
var value = obj[key];
// ...
});

How to get the 'Value' using 'Key' from json in Javascript/Jquery

I have the following Json string. I want to get the 'Value' using 'Key', something like
giving 'BtchGotAdjust' returns 'Batch Got Adjusted';
var jsonstring=
[{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"},]
Wow... Looks kind of tough! Seems like you need to manipulate it a bit. Instead of functions, we can create a new object this way:
var jsonstring =
[{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"},];
var finalJSON = {};
for (var i in jsonstring)
finalJSON[jsonstring[i]["Key"]] = jsonstring[i]["Value"];
You can use it using:
finalJSON["BtchGotAdjust"]; // Batch Got Adjusted
As you have an array in your variable, you have to loop over the array and compare against the Key-Property of each element, something along the lines of this:
for (var i = 0; i < jsonstring.length; i++) {
if (jsonstring[i].Key === 'BtchGotAdjust') {
console.log(jsonstring[i].Value);
}
}
By the way, I think your variable name jsonstring is a little misleading. It does not contain a string. It contains an array. Still, the above code should give you a hint in the right direction.
Personally I would create a map from the array and then it acts like a dictionary giving you instantaneous access. You also only have to iterate through the array once to get all the data you need:
var objectArray = [{"Key":"BtchGotAdjust","Value":"Batch Got Adjusted"},{"Key":"UnitToUnit","Value":"Unit To Unit"}]
var map = {}
for (var i=0; i < objectArray.length; i++){
map[objectArray[i].Key] = objectArray[i]
}
console.log(map);
alert(map["BtchGotAdjust"].Value)
alert(map["UnitToUnit"].Value)
See js fiddle here: http://jsfiddle.net/t2vrn1pq/1/

Access to a certain part of JSON data with jQuery

So i have this JSON:
{
"id_u":"1",
"nombre_usuario":"JESUS",
"apellido_paterno_usuario":"DIAZ"
}
I just want to access to the fields names
id_u,_nombre_usuario,apellido_paterno_usuario
And then, create an array with that info.
How can i do that?
Thanks guys
Do this way :
var keyValuePair = {
"id_u":"1",
"nombre_usuario":"JESUS",
"apellido_paterno_usuario":"DIAZ"
};
var arr =new Array();
for (key in keyValuePair){
arr.push(key); // for keys
// arr.push(keyValuePair[key]); // for values
}
Use .each() to parse JSON.
Try this:
var keyArray = [];
var a = {
"id_u":"1",
"nombre_usuario":"JESUS",
"apellido_paterno_usuario":"DIAZ"
};
$.each(a,function(i,v){
keyArray.push(i); // i is json key and v is json value.
});
console.log(keyArray);
DEMO
Object.keys(jsonObject) is enough.

JSON conversion issue

I am trying (in Javascript an Coldfusion) to convert:
{"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"},
Into this:
{ member,book,journal,new_member,cds}
Notice that I am trying to eliminate quotes.
Is it possible to achieve this? How can I do it?
Ok, so this:
{"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"}
is JSON.
To convert to a CF struct, you'd go like this:
myStruct = deserializeJSON('{"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"}');
(Note my examples assume we're operating within a <CFSCRIPT> block.)
Now you've got a simple struct with key/value pairs. But you want a list of the values. So let's make an empty string, then append all the struct values to it:
myList = "";
for (k IN myStruct) {
myList = listAppend(myList,myStruct[k]);
}
Boom. myList should now be "member,book,journal,new_member,cds"
Wrap it in curly braces if you really want to.
myList = "{"&myList&"}";
First of all, I have to thank you for your replies. But some of you have to be more polite with newbies.
var tata = {"val1":"member","val2":"book","val3":"journal","val4":"new_member","val5":"cds"}
var arr=[]
for (var i in tata) {
arr.push(tata[i])
};
console.log(arr);
wrd = new Array(arr)
var joinwrd = wrd.join(",");
console.log('{' + joinwrd + '}');

Create JSON string from javascript for loop

I want to create a JSON string from a javascript for loop. This is what I tried to do (which gives me something that looks like a JSON string), but it does not work.
var edited = "";
for(var i=1;i<POST.length-1;i++) {
edited += '"'+POST[i].name+'":"'+POST[i].value+'",';
}
It gives me this:
"type":"empty","name":"email-address","realname":"Email Address","status":"empty","min":"empty","max":"empty","dependson":"empty",
This does not work if I try to convert it into a JSON object later.
Two problems:
You want an object, so the JSON string has to start with { and end with }.
There is a trailing , which may be recognized as invalid.
It's probably better to use a library, but to correct your code:
Change var edited = ""; to var edited = "{"; to start your JSON string with a {
Add edited = edited.slice(0, -1); after the for loop to remove the trailing comma.
Add edited += "}"; after the previous statement to end your JSON string with a }
Your final code would be:
var edited = "{";
for(var i=1;i<POST.length-1;i++) {
edited += '"'+POST[i].name+'":"'+POST[i].value+'",';
}
edited = edited.slice(0, -1);
edited += "}";
Again, it's best to use a library (e.g. JSON.stringify) by making an object with a for loop, adding properties by using POST[i].name as a key and POST[i].value as the value, then using the library to convert the object to JSON.
Also, you are starting with index 1 and ending with index POST.length-2, therefore excluding indices 0 (the first value) and POST.length-1 (the last value). Is that what you really want?
//dummy data
var post=[{name:'name1',value:1},{name:'name2',value:2}];
var json=[];
for(var i=0;i<post.length;i++)
{
var temp={};
temp[post[i].name]=post[i].value;
json.push(temp);
}
var stringJson = JSON.stringify(json);
alert(stringJson );
http://jsfiddle.net/3mYux/
You have extra comma in your JSON string. JSON string format: {"JSON": "Hello, World"}
var edited = "{";
for(var i=1;i<POST.length-1;i++) {
edited += '"'+POST[i].name+'":"'+POST[i].value+'",';
}
// remove last comma:
edited = edited.substring(0, edited.length-1) + "}";
Can't you just build up a hash and do toString on the hash? Something like this:
var edited = {};
for(var i=0;i<POST.length-1;i++) {
edited[POST[i].name] = POST[i].value;
}
Or maybe JSON.stringify is what you are looking for: http://www.json.org/js.html

Categories

Resources