How to get the second data of this JSON in jQuery? - javascript

How can I get the second data of this JSON - I am beta. in jQuery?
{"alpha":["I am alpha"],"beta":["I am beta."]}

You can go through array and search for keys what you want... but dont forget to encode json string
$data= json.encode($input)
foreach($data as $key => $val)
{
if($key=='beta')
do something
else
do something else
}
I hope it help you.

Assuming that your json is in a string variable as:
var data = '{"alpha":["I am alpha"],"beta":["I am beta."]}';
You can parse the string as a json object and then access the content like this:
json = JSON.parse(data);
//or if you strictly need to use jQuery
json = $.parseJSON(data);
alert(json.alpha[0]);
alert(json.beta[0]);
If you don't know which is the json content you can iterate through json object like this:
for (var key in json) {
if (json.hasOwnProperty(key)) {
alert(key + " -> " + json[key]);
}
}

Finally I come up with this
Step 1: Json parsed,
Step 2 : Declared in another string
Step 3 : And then looped inside each entry
obj=JSON.parse(data);
var error_string='';
$.each(obj, function(entry) {
error_string+=obj[entry]+'<br/>';
});
$('#stage').html(error_string);
}
And then i got the values that is inside, Now i can able to get the values inside the object even for n numbers.

Related

Javascript: How to parse a json array without knowing the key name?

I want to parse the following json:
{"key_410441":{"hashId":"hash123","tube_id":"4accdefk31"}}
Where key_410441 is the entry's name representing the object's value, and the following array is the object's data.
How can I retrieve it's value?
function defined(json) {
for (var i in json) {
var objId = json[i]. ????
}
}
Like Robo Robok said, use Object.keys(object)
if your json look like {"key_410441":{"hashId":"hash123","tube_id":"4accdefk31"}}
function defined(json) {
var hashId = json[Object.keys(json)[0]].hashId
var tube_id = json[Object.keys(json)[0]].tube_id
}
}
you can use shortcut json[Object.keys(json)] because you have olny one object
key_410441
Object keys are returned in form of an array by Object.keys(object)
I suppose you are using jquery and ajax to get a json from an external file. Then the piece of code would be:-
$.getJSON("aa.json", function(data) {
var obj = Object.keys(data),
json = data[obj];
for(var s in json) {
console.log(json[s]);
}
});

Store values in javascript object with same keys

I have the following code to extract values from a JSON response. What I am trying to do is store the data in a similar way to how you would with an associative array in php. Apologies for the code being inefficient. The array comments written down are how I would like it to look in the object.
$.each(responseData, function(k1,v1){
if(k1 == "0"){
$.each(v1, function(k2,v2){
$.each(v2, function(k3, v3){
if(k3 == "val"){
//store in object here
//Array1 = array("time"=>k2, "iVal"=>v3)
console.log(k3 + v3 + k2);
}else{
//Array2 = array("time"=>k2, "aVal"=>v3)
console.log(k3 + v3 + k2);
}
});
});
}
});
So all the information is there but I am not sure how to store each instance for the values in an object. I did try store it like this:
//obj created outside
obj1.date = k2;
obj2.iVal = v3;
But doing this clearly overwrote every time, and only kept the last instance so I am wondering how can I do it so that all values will be stored?
Edit: Added input and output desired.
Input
{"0":{"18.00":{"iVal":85.27,"aVal":0.24},"19.00":{"iVal":85.27,"aVal":0.36},"20.00":{"iVal":0,"aVal":0}}, "success":true}
Desired output
array1 = {"time":"18.00", "iVal":85.27},{"time":"19.00", "iVal":85.27},{"time":"20.00", "iVal":0}
array2 = {"time":"18.00", "aVal":0.24},{"time":"19.00", "aVal":0.36},{"time":"20.00", "aVal":0}
try this :
var g1=[];
var g2=[];
for ( a in o[0])
{
g1.push({time:a , iVal:o[0][a]['iVal']})
g2.push({time:a , aVal:o[0][a]['aVal']})
}
http://jsbin.com/qividoti/3/edit
a json response can be converted back to a js object literal by calling JSON.parse(jsonString) inside the success callback of your ajax call.
from then on there is no need for iterating over that object since you navigate it like any other js object which is can be done in two ways either
the js way -> dot notation
var obj = JSON.parse(jsonStirng);
var value = obj.value;
or like a php array
var value = obj["value"];

Get json data from a file

I wan't to get data from a json file without knowing exacly where the data is:
I have this json
var names= [
{
"category":"category1" ,
"name1":"david",
"name2":"jhon",
"name3":"peter"
},
{
"category":"category2" ,
"name1":"Smith" ,
"name2":"Anna",
}
]
suppose i have a string variable:
var str='category2';
how can i get category2.name1 using the variable?
I don't want to use names[1].name1 because i don't know whats in str and i want to avoid using for loop.
There are some build-in functions that may help you. For example:
var matchingElements = names.filter(function(object, index, array) {
return object.category == str;
});
What you're looking for will always be in matchingElements[0].name1 if matchingElements.length > 0.

Printing JSON Dictionary in JavaScript

I am getting the data from an API using JavaScript.
The statement console.log(json[0]) gives the result:
{"id":"1","username":"ghost","points":"5","kills":"18","xp":"10","diamonds":"0","level":"1","missionscomplete":"1"}
Now I am trying to print the individual elements of this dictionary. How do I do this ? My code is below:
function loadLeaderboard(){
$.get("http://localhost:8888/l4/public/api/v1/getLeaderboard",function(data){
var json = $.parseJSON(data);
console.log(json[0]);
$.each(json[i], function(key, data) {
console.log(key + ' -> ' + data);
});
});
}
EDIT:
The value of data as returned by the API is
["{\"id\":\"1\",\"username\":\"ghost\",\"points\":\"5\",\"kills\":\"18\",\"xp\":\"10\",\"diamonds\":\"0\",\"level\":\"1\",\"missionscomplete\":\"1\"}","{\"id\":\"2\",\"username\":\"seconduser\",\"points\":\"0\",\"kills\":\"3\",\"xp\":\"0\",\"diamonds\":\"0\",\"level\":\"0\",\"missionscomplete\":\"0\"}","{\"id\":\"3\",\"username\":\"goat\",\"points\":\"12\",\"kills\":\"13\",\"xp\":\"14\",\"diamonds\":\"10\",\"level\":\"10\",\"missionscomplete\":\"4\"}"]
The value in json after the operation var json = $.parseJSON(data); is
["{"id":"1","username":"ghost","points":"5","kills":…diamonds":"0","level":"1","missionscomplete":"1"}", "{"id":"2","username":"seconduser","points":"0","ki…diamonds":"0","level":"0","missionscomplete":"0"}", "{"id":"3","username":"goat","points":"12","kills":…amonds":"10","level":"10","missionscomplete":"4"}"]
You can just use stringify method of JSON-
console.log(JSON.stringify(json[0]));
Update
Your JSON data is a mess. It's not in the format you want. It should be an array of objects, but instead it is an array of strings, where each of those strings is the JSON representation of one of your user objects.
You could decode this in your JavaScript code, but you shouldn't have to. The JSON API should be fixed to generate a reasonable JSON object.
I don't know what language your server code is in, but it must be doing something like this pseudocode:
array = []
for each userObject in leaderBoard:
userJson = toJSON( userObject )
array.push( userJson )
jsonOutput = toJSON( array )
Instead, the code should look more like this:
array = []
for each userObject in leaderBoard:
array.push( userObject )
jsonOutput = toJSON( array )
In other words, the way to generate the JSON you want in most languages is to create an object or array with the structure you need, and then call the language's toJSON function (or whatever function you use) on that object or array. Let it generate all of the JSON in one fell swoop. Don't generate JSON for each individual element of your array and then generate JSON again for the entire array as a whole. That gives you an array of strings where you want an array of objects.
Original answer
What you're asking for is not what you really want to do.
Your JSON response returns an array of user objects, correct? That's why json[0] is a single object.
You probably want to loop over that array, but you don't loop over the individual objects in the array. You simply reference their properties by name.
Also, instead of using $.get() and $.parseJSON(), you can use $.getJSON() which parses it for you.
And one other tip: don't put the hostname and port in your URL. Use a relative URL instead, and then you can use the same URL in both development and production.
So for test purposes, let's say you want to log the id, username, and points for each user in your leaderboard JSON array. You could do it like this:
function loadLeaderboard() {
var url = '/l4/public/api/v1/getLeaderboard';
$.getJSON( url, function( leaders ) {
// leaders is an array of user objects, so loop over it
$.each( leaders, function( i, user ) {
// get the properties directly for the current user
console.log( user.id, user.username, user.points );
});
});
}
json[0] is an object, so you want to loop over the keys:
var o = json[0];
for (var key in o) {
if (o.hasOwnProperty(key)) {
console.log(key, o[key]);
}
}
Working fiddle: http://jsfiddle.net/UTyDa/
jQuery.each() is probably the easiest way, check this out: http://api.jquery.com/jQuery.each/
eg
$.each(json[0], function(key, data) {
console.log(key + ' -> ' + data);
});
EDIT:
What's the result of the following?
function loadLeaderboard(){
$.get("http://localhost:8888/l4/public/api/v1/getLeaderboard",function(data){
var json = $.parseJSON(data);
console.log(json[0]);
for(var i = 0; i < json.length; i++) {
$.each(json[i], function(key, data) {
console.log(key + ' -> ' + data);
});
}
});
}
EDIT 2: 'data' returned as array.
function loadLeaderboard(){
$.get("http://localhost:8888/l4/public/api/v1/getLeaderboard", function(data){
for(var i = 0; i < data.length; i++) {
var json = $.parseJSON(data[i]);
console.log('Data for index: ' + i);
$.each(json, function(key, val) {
console.log(key + ' -> ' + val);
});
}
});
}

when saving an array of objects as a JSON, I need to use the following format in Sample.txt to not run into parsing errors:

when saving an array of objects as a JSON, you need to use the following format in Sample.txt to not run into parsing errors:
[{"result":"\"21 inches = 21 inches\"","count":1},{"result":"\"32 inches = 32 inches\"","count":2}]
I'm new to JSON and searching over this for since last 4 days. I tried different approaches of storing an array of objects but no success. My first and simplest try is like this:
function createData() {
//original, single json object
var dataToSave = {
"result": '"' + toLength.innerText +'"',
"count": counter
};
//save into an array:
var dataArray = { [] }; //No idea how to go ahead..
var savedData = JSON.stringify(dataToSave);
writeToFile(filename, savedData); //filename is a text file. Inside file, I want to save each json object with , in between. So It can be parsed easily and correctly.
}
function readData(data) {
var dataToRead = JSON.parse(data);
var message = "Your Saved Conversions : ";
message += dataToRead.result;
document.getElementById("savedOutput1").innerText = message;
}
To make an array from your object, you may do
var dataArray = [dataToSave];
To add other elements after that, you may use
dataArray.push(otherData);
When you read it, as data is an array, you can't simply use data.result. You must get access to the array's items using data[0].result, ... data[i].result...

Categories