Looping through a json object in javascript - 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);
});

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);
});
});

loop for fetching json data in html [duplicate]

On the jQuery AJAX success callback I want to loop over the results of the object. This is an example of how the response looks in Firebug.
[
{"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
{"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
{"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
]
How can I loop over the results so that I would have access to each of the elements?
I have tried something like below but this does not seem to be working.
jQuery.each(data, function(index, itemData) {
// itemData.TEST1
// itemData.TEST2
// itemData.TEST3
});
you can remove the outer loop and replace this with data.data:
$.each(data.data, function(k, v) {
/// do stuff
});
You were close:
$.each(data, function() {
$.each(this, function(k, v) {
/// do stuff
});
});
You have an array of objects/maps so the outer loop iterates over those. The inner loop iterates over the properties on each object element.
You can also use the getJSON function:
$.getJSON('/your/script.php', function(data) {
$.each(data, function(index) {
alert(data[index].TEST1);
alert(data[index].TEST2);
});
});
This is really just a rewording of ifesdjeen's answer, but I thought it might be helpful to people.
If you use Fire Fox, just open up a console (use F12 key) and try out this:
var a = [
{"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
{"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
{"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
];
$.each (a, function (bb) {
console.log (bb);
console.log (a[bb]);
console.log (a[bb].TEST1);
});
hope it helps
For anyone else stuck with this, it's probably not working because the ajax call is interpreting your returned data as text - i.e. it's not yet a JSON object.
You can convert it to a JSON object by manually using the parseJSON command or simply adding the dataType: 'json' property to your ajax call. e.g.
jQuery.ajax({
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: data,
dataType: 'json', // ** ensure you add this line **
success: function(data) {
jQuery.each(data, function(index, item) {
//now you can access properties using dot notation
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});
Access the json array like you would any other array.
for(var i =0;i < itemData.length-1;i++)
{
var item = itemData[i];
alert(item.Test1 + item.Test2 + item.Test3);
}
This is what I came up with to easily view all data values:
var dataItems = "";
$.each(data, function (index, itemData) {
dataItems += index + ": " + itemData + "\n";
});
console.log(dataItems);
Try jQuery.map function, works pretty well with maps.
var mapArray = {
"lastName": "Last Name cannot be null!",
"email": "Email cannot be null!",
"firstName": "First Name cannot be null!"
};
$.map(mapArray, function(val, key) {
alert("Value is :" + val);
alert("key is :" + key);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
if you don't want alert, that is u want html, then do this
...
$.each(data, function(index) {
$("#pr_result").append(data[index].dbcolumn);
});
...
NOTE: use "append" not "html" else the last result is what you will be seeing on your html view
then your html code should look like this
...
<div id="pr_result"></div>
...
You can also style (add class) the div in the jquery before it renders as html
I use .map for foreach. For example
success: function(data) {
let dataItems = JSON.parse(data)
dataItems = dataItems.map((item) => {
return $(`<article>
<h2>${item.post_title}</h2>
<p>${item.post_excerpt}</p>
</article>`)
})
},
If you are using the short method of JQuery ajax call function as shown below, the returned data needs to be interpreted as a json object for you to be able to loop through.
$.get('url', function(data, statusText, xheader){
// your code within the success callback
var data = $.parseJSON(data);
$.each(data, function(i){
console.log(data[i]);
})
})
I am partial to ES2015 arrow function for finding values in an array
const result = data.find(x=> x.TEST1 === '46');
Checkout Array.prototype.find() HERE
$each will work.. Another option is jQuery Ajax Callback for array result
function displayResultForLog(result) {
if (result.hasOwnProperty("d")) {
result = result.d
}
if (result !== undefined && result != null) {
if (result.hasOwnProperty('length')) {
if (result.length >= 1) {
for (i = 0; i < result.length; i++) {
var sentDate = result[i];
}
} else {
$(requiredTable).append('Length is 0');
}
} else {
$(requiredTable).append('Length is not available.');
}
} else {
$(requiredTable).append('Result is null.');
}
}

aAccessing key values in JSON

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;

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);
});
}
});

Serializing to JSON in jQuery [duplicate]

This question already has answers here:
Serializing an object to JSON
(4 answers)
Closed 5 years ago.
I need to serialize an object to JSON. I'm using jQuery. Is there a "standard" way to do this?
My specific situation: I have an array defined as shown below:
var countries = new Array();
countries[0] = 'ga';
countries[1] = 'cd';
...
and I need to turn this into a string to pass to $.ajax() like this:
$.ajax({
type: "POST",
url: "Concessions.aspx/GetConcessions",
data: "{'countries':['ga','cd']}",
...
JSON-js - JSON in JavaScript.
To convert an object to a string, use JSON.stringify:
var json_text = JSON.stringify(your_object, null, 2);
To convert a JSON string to object, use JSON.parse:
var your_object = JSON.parse(json_text);
It was recently recommended by John Resig:
...PLEASE start migrating
your JSON-using applications over to
Crockford's json2.js. It is fully
compatible with the ECMAScript 5
specification and gracefully degrades
if a native (faster!) implementation
exists.
In fact, I just landed a change in jQuery yesterday that utilizes the
JSON.parse method if it exists, now
that it has been completely specified.
I tend to trust what he says on JavaScript matters :)
All modern browsers (and many older ones which aren't ancient) support the JSON object natively. The current version of Crockford's JSON library will only define JSON.stringify and JSON.parse if they're not already defined, leaving any browser native implementation intact.
I've been using jquery-json for 6 months and it works great. It's very simple to use:
var myObj = {foo: "bar", "baz": "wockaflockafliz"};
$.toJSON(myObj);
// Result: {"foo":"bar","baz":"wockaflockafliz"}
Works on IE8+
No need for jQuery, use:
JSON.stringify(countries);
I haven't used it but you might want to try the jQuery plugin written by Mark Gibson
It adds the two functions: $.toJSON(value), $.parseJSON(json_str, [safe]).
No, the standard way to serialize to JSON is to use an existing JSON serialization library. If you don't wish to do this, then you're going to have to write your own serialization methods.
If you want guidance on how to do this, I'd suggest examining the source of some of the available libraries.
EDIT: I'm not going to come out and say that writing your own serliazation methods is bad, but you must consider that if it's important to your application to use well-formed JSON, then you have to weigh the overhead of "one more dependency" against the possibility that your custom methods may one day encounter a failure case that you hadn't anticipated. Whether that risk is acceptable is your call.
I did find this somewhere. Can't remember where though... probably on StackOverflow :)
$.fn.serializeObject = function(){
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};
If you don't want to use external libraries there is .toSource() native JavaScript method, but it's not perfectly cross-browser.
Yes, you should JSON.stringify and JSON.parse your Json_PostData before calling $.ajax:
$.ajax({
url: post_http_site,
type: "POST",
data: JSON.parse(JSON.stringify(Json_PostData)),
cache: false,
error: function (xhr, ajaxOptions, thrownError) {
alert(" write json item, Ajax error! " + xhr.status + " error =" + thrownError + " xhr.responseText = " + xhr.responseText );
},
success: function (data) {
alert("write json item, Ajax OK");
}
});
The best way is to include the polyfill for JSON object.
But if you insist create a method for serializing an object to JSON notation (valid values for JSON) inside the jQuery namespace, you can do something like this:
Implementation
// This is a reference to JSON.stringify and provides a polyfill for old browsers.
// stringify serializes an object, array or primitive value and return it as JSON.
jQuery.stringify = (function ($) {
var _PRIMITIVE, _OPEN, _CLOSE;
if (window.JSON && typeof JSON.stringify === "function")
return JSON.stringify;
_PRIMITIVE = /string|number|boolean|null/;
_OPEN = {
object: "{",
array: "["
};
_CLOSE = {
object: "}",
array: "]"
};
//actions to execute in each iteration
function action(key, value) {
var type = $.type(value),
prop = "";
//key is not an array index
if (typeof key !== "number") {
prop = '"' + key + '":';
}
if (type === "string") {
prop += '"' + value + '"';
} else if (_PRIMITIVE.test(type)) {
prop += value;
} else if (type === "array" || type === "object") {
prop += toJson(value, type);
} else return;
this.push(prop);
}
//iterates over an object or array
function each(obj, callback, thisArg) {
for (var key in obj) {
if (obj instanceof Array) key = +key;
callback.call(thisArg, key, obj[key]);
}
}
//generates the json
function toJson(obj, type) {
var items = [];
each(obj, action, items);
return _OPEN[type] + items.join(",") + _CLOSE[type];
}
//exported function that generates the json
return function stringify(obj) {
if (!arguments.length) return "";
var type = $.type(obj);
if (_PRIMITIVE.test(type))
return (obj === null ? type : obj.toString());
//obj is array or object
return toJson(obj, type);
}
}(jQuery));
Usage
var myObject = {
"0": null,
"total-items": 10,
"undefined-prop": void(0),
sorted: true,
images: ["bg-menu.png", "bg-body.jpg", [1, 2]],
position: { //nested object literal
"x": 40,
"y": 300,
offset: [{ top: 23 }]
},
onChange: function() { return !0 },
pattern: /^bg-.+\.(?:png|jpe?g)$/i
};
var json = jQuery.stringify(myObject);
console.log(json);
It's basically 2 step process:
First, you need to stringify like this:
var JSON_VAR = JSON.stringify(OBJECT_NAME, null, 2);
After that, you need to convert the string to Object:
var obj = JSON.parse(JSON_VAR);
One thing that the above solutions don't take into account is if you have an array of inputs but only one value was supplied.
For instance, if the back end expects an array of People, but in this particular case, you are just dealing with a single person. Then doing:
<input type="hidden" name="People" value="Joe" />
Then with the previous solutions, it would just map to something like:
{
"People" : "Joe"
}
But it should really map to
{
"People" : [ "Joe" ]
}
To fix that, the input should look like:
<input type="hidden" name="People[]" value="Joe" />
And you would use the following function (based off of other solutions, but extended a bit)
$.fn.serializeObject = function() {
var o = {};
var a = this.serializeArray();
$.each(a, function() {
if (this.name.substr(-2) == "[]"){
this.name = this.name.substr(0, this.name.length - 2);
o[this.name] = [];
}
if (o[this.name]) {
if (!o[this.name].push) {
o[this.name] = [o[this.name]];
}
o[this.name].push(this.value || '');
} else {
o[this.name] = this.value || '';
}
});
return o;
};

Categories

Resources