aAccessing key values in JSON - javascript

I have a JSON response like this. I want to access the rollbacktoken key. How should I do it ?
{"query":{
"pages":{
"5":{
"pageid":5,
"ns":0,
"title":"Abhishek",
"revisions":
[{
"revid":376,
"parentid":360,
"user":"Abhishek",
"timestamp":"2015-02-15T10:29:55Z",
"comment":"",
"rollbacktoken":"232e77d570434db159dbbd3d43d3ea4e+\\"
}]
}
}
}
}
I have tried:
var a = JSON.stringify(query.pages.revisions.rollbacktoken);

figured it out
var json = JSON.parse(data);
console.log(json.query.pages['5'].revisions['0'].rollback);

var json = JSON.parse(data);
json.getJSONObject("query").getJSONObject("pages")..getJSONObject("5").getJSONObject("revisions").rollbacktoken;

Related

How to read JSON Response from URL and use the keys and values inside Javascript (array inside array)

My Controller Function:
public function displayAction(Request $request)
{
$stat = $this->get("app_bundle.helper.display_helper");
$displayData = $stat->generateStat();
return new JsonResponse($displayData);
}
My JSON Response from URL is:
{"Total":[{"date":"2016-11-28","selfies":8},{"date":"2016-11-29","selfies":5}],"Shared":[{"date":"2016-11-28","shares":5},{"date":"2016-11-29","shares":2}]}
From this Response I want to pass the values to variables (selfie,shared) in javascript file like:
$(document).ready(function(){
var selfie = [
[(2016-11-28),8], [(2016-11-29),5]]
];
var shared = [
[(2016-11-28),5], [(2016-11-29),2]]
];
});
You can try like this.
First traverse the top object data and then traverse each property of the data which is an array.
var data = {"total":[{"date":"2016-11-28","selfies":0},{"date":"2016-11-29","selfies":2},{"date":"2016-11-30","selfies":0},{"date":"2016-12-01","selfies":0},{"date":"2016-12-02","selfies":0},{"date":"2016-12-03","selfies":0},{"date":"2016-12-04","selfies":0}],"shared":[{"date":"2016-11-28","shares":0},{"date":"2016-11-29","shares":0},{"date":"2016-11-30","shares":0},{"date":"2016-12-01","shares":0},{"date":"2016-12-02","shares":0},{"date":"2016-12-03","shares":0},{"date":"2016-12-04","shares":0}]}
Object.keys(data).forEach(function(k){
var val = data[k];
val.forEach(function(element) {
console.log(element.date);
console.log(element.selfies != undefined ? element.selfies : element.shares );
});
});
Inside your callback use the following:
$.each(data.total, function(i, o){
console.log(o.selfies);
console.log(o.date);
// or do whatever you want here
})
Because you make the request using jetJSON the parameter data sent to the callback is already an object so you don't need to parse the response.
Try this :
var text ='{"Total":[{"date":"2016-11-28","selfies":0},{"date":"2016-11-29","selfies":2}],"Shared":[{"date":"2016-11-28","shares":0},{"date":"2016-11-29","shares":0}]}';
var jsonObj = JSON.parse(text);
var objKeys = Object.keys(jsonObj);
for (var i in objKeys) {
var totalSharedObj = jsonObj[objKeys[i]];
if(objKeys[i] == 'Total') {
for (var j in totalSharedObj) {
document.getElementById("demo").innerHTML +=
"selfies on "+totalSharedObj[j].date+":"+totalSharedObj[j].selfies+"<br>";
}
}
if(objKeys[i] == 'Shared') {
for (var k in totalSharedObj) {
document.getElementById("demo").innerHTML +=
"shares on "+totalSharedObj[k].date+":"+totalSharedObj[k].shares+"<br>";
}
}
}
<div id="demo">
</div>
I did a lot of Research & took help from other users and could finally fix my problem. So thought of sharing my solution.
$.get( "Address for my JSON data", function( data ) {
var selfie =[];
$(data.Total).each(function(){
var tmp = [
this.date,
this.selfies
];
selfie.push(tmp);
});
var shared =[];
$(data.Shared).each(function(){
var tmp = [
this.date,
this.shares
];
shared.push(tmp);
});
});

Javascript: parse json to list

I am new to javascript, sorry for silly question and possible duplicate. Please suggest me efficient way of parsing json. I would like to fetch list of strings Maktg:
{
"d":{
"results":[
{
"Maktg":"BATTERY",
"W":"1000",
"IS":"",
"IM":"",
"IW":"",
"__metadata":{
"type":"s",
"uri":"https://some_url)"
},
"IMaktg":"",
"Matnr":"0001",
"Stlan":"1"
},
{
"Maktg":"CONTROL",
//etc...
We have a JSON:
{
"d":{
"results":[
{
"Maktg":"BATTERY",
"W":"1000",
"IS":"",
"IM":"",
"IW":"",
"__metadata":{
"type":"s",
"uri":"https://some_url"
},
"IMaktg":"",
"Matnr":"0001",
"Stlan":"1"
}
]
}
}
Lest convert string JSON into more useful JavaScript object:
The JSON.parse() method parses a string as JSON, optionally
transforming the value produced by parsing.
var
jsonStr = '{"d":{"results":[{"Maktg":"BATTERY","W":"1000","IS":"","IM":"","IW":"","__metadata":{"type":"s","uri":"https://some_url"},"IMaktg":"","Matnr":"0001","Stlan":"1"}]}}';
jsonObj = JSON.parse(jsonStr),
results = jsonObj.d.results;
for (var i in results) {
console.log(results[i]['Maktg']);
/*
results[i]['W']
results[i]['IS']
results[i]['IM']
results[i]['__metadata']['type']
and etc...
*/
}
Try this:
var jsonArray = yourJSON.d.results;
var results = [];
jsonArray.forEach(function(object){
results.push(object.Maktg);
}
console.log(results);
Please try to get output with JSON.parse like this.
var getData = JSON.parse(data);
for(i=0;i<getData.d["results"].length;i++)
{
alert(getData.d["results"][i].Maktg);
alert(getData.d["results"][i].W);
//etc...
}

Looping through a json object in javascript

I am trying to look through an object, but based on the structure I do not know how to get to the data.
Object:
{
"177":{
"text":"test text",
"user_name":"Admin",
"date":"1385494358",
"docs":{
"document_name": [
"marketing_service",
"maintenance_service",
"development_service"],
"document_type":[
"png",
"png",
"png"]
}
},
"174":{
"text":"Some more images",
"user_name":"Admin",
"date":"1385493618",
"docs":{
"document_name": [
"marketing_service16",
"maintenance_service53"],
"document_type":[
"png","png"]
}
}
}
The loop I am attempting in jQuery
var obj = $.parseJSON(data);
$(obj).each(function(index, note) {
console.log(note.text + note.user_name + note.date_created);
});
It is returning undefined. What am I doing wrong?
Try like this
var obj = $.parseJSON(data);
for(var n in obj){
var note = obj[n]
console.log(note.text + note.user_name + note.date_created);
}
To loop through a json object just use a for loop.
The way you are doing it will return errors because it is trying to select that json object from the page which does not exist.
Sample code:
var obj = $.parseJSON(data); //assuming `data` is a string
for(index in obj) {
var note = obj[index];
console.log(note.text + note.user_name + note.date_created);
};
its a little better to do it like this:
$.each(obj, function ( index, note ) {
console.log( note.text + note.user_name + note.date_created );
});
this should give you what you need
Working Demo: http://jsfiddle.net/gZ7pd/ or for document http://jsfiddle.net/NGqfB/
Issue is parseJson on the object which is Json.
in the demo above the var obj = $.parseJSON(data); returns null, if I use data it will work.
Hope this helps ;)
Code
var data = {
"177":{
"text":"test text",
"user_name":"Admin",
"date":"1385494358",
"docs":{
"document_name": [
"marketing_service",
"maintenance_service",
"development_service"],
"document_type":[
"png",
"png",
"png"]
}
},
"174":{
"text":"Some more images",
"user_name":"Admin",
"date":"1385493618",
"docs":{
"document_name": [
"marketing_service16",
"maintenance_service53"],
"document_type":[
"png","png"]
}
}
};
var obj = $.parseJSON(data);
alert(obj)
$.each(data,function(index, note) {
alert(note.text + note.user_name + note.date_created);
});

Getting property key from json object

Preamble: I'm Italian, sorry for my bad English.
I need to retrieve the name of the property from a json object using javascript/jquery.
for example, starting from this object:
{
"Table": {
"Name": "Chris",
"Surname": "McDonald"
}
}
is there a way to get the strings "Name" and "Surname"?
something like:
//not working code, just for example
var jsonobj = eval('(' + previouscode + ')');
var prop = jsonobj.Table[0].getPropertyName();
var prop2 = jsonobj.Table[1].getPropertyName();
return prop + '-' + prop2; // this will return 'Name-Surname'
var names = [];
for ( var o in jsonobj.Table ) {
names.push( o ); // the property name
}
In modern browsers:
var names = Object.keys( jsonobj.Table );
You can browse the properties of the object:
var table = jsonobj.Table;
for (var prop in table) {
if (table.hasOwnProperty(prop)) {
alert(prop);
}
}
The hasOwnProperty test is necessary to avoid including properties inherited from the prototype chain.
In jquery you can fetch it like this:
$.ajax({
url:'path to your json',
type:'post',
dataType:'json',
success:function(data){
$.each(data.Table, function(i, data){
console.log(data.name);
});
}
});

How to parse json response from Bigquery results?

I tried sample javascript code to call Google bigQuery API ( https://developers.google.com/bigquery/docs/authorization#client-side-javascript )
Js:
function runQuery() {
var request = gapi.client.bigquery.jobs.query({
'projectId': project_id,
'timeoutMs': '30000',
'query': 'SELECT TOP(repository_language, 5) as language, COUNT(*) as count FROM [publicdata:samples.github_timeline] WHERE repository_language != "";'
});
request.execute(function(response) {
console.log(response);
var results = response.result.rows ;
$('#result_box').html(JSON.stringify(results, null));
});
}
Above big query returns :
[{"f":[{"v":"JavaScript"},{"v":"949899"}]},{"f":[{"v":"Ruby"},{"v":"640659"}]},{"f":[{"v":"Java"},{"v":"568202"}]},{"f":[{"v":"Python"},{"v":"484852"}]},{"f":[{"v":"PHP"},{"v":"453830"}]}]
Please help me how to parse the values from above results in JSON Format ?
{"JavaScript": "949899", "Ruby": "640659", "Java": "568202", "Python": "484852", "PHP": "453830" }
Eval is a security risk.
var text = '[{"f":[{"v":"JavaScript"},{"v":"949899"}]},{"f":[{"v":"Ruby"},{"v":"640659"}]},{"f":[{"v":"Java"},{"v":"568202"}]},{"f":[{"v":"Python"},{"v":"484852"}]},{"f":[{"v":"PHP"},{"v":"453830"}]}]';
myData = JSON.parse(text);
alert(myData[4].f[0].v);​
http://jsfiddle.net/jv7vm/
var a='[{"f":[{"v":"JavaScript"},{"v":"949899"}]},{"f":[{"v":"Ruby"},{"v":"640659"}]},{"f":[{"v":"Java"},{"v":"568202"}]},{"f":[{"v":"Python"},{"v":"484852"}]},{"f":[{"v":"PHP"},{"v":"453830"}]}]';
var evala=eval('('+a+')');
for(i=0;i<evala.length;i++)
{
document.write(evala[i].f[0].v+' '+evala[i].f[1].v+'<br>');
}
Got answer from below javascript
var total = response.result.totalRows;
var data = [];
for(i=0; i < total; i++){
data[i]= [ response.rows[i].f[0]["v"], response.rows[i].f[1]["v"] ];
}
console.log(data);

Categories

Resources