Parsing JSON object in JavaScript/JQuery - javascript

I have a Json object as following.
{
"firstName":"John",
"lastName":"Doe"
"123":"456"
}
I want to access they keys and value. After reaching, I will set them into fields. But I don’t why it doesn’t work. I’ve checked its syntax has no problem.
What I’ve tried,
$(document).ready(function f() {
$.ajax('http://soner.dev/test.txt', {
success: function(data, status, xhr) {
$(data).each(function(i,val)
{
$.each(val,function(key,val)
{
console.log(key + " : " + val);
alert(key + " : " + val);
$('#{key}').val(val);
});
});
setTimeout(f, 1000); // refresh the data at each second(data changes at each 1sec)
}
});
});
By the way, $('#{key}').val(val); in which I try to use Template Literals.

You've got an object there, not an array. In JSON, objects are wrapped with { and } and have named properties like "firstName" etc. Arrays are wrapped with [ and ] and have numbered indexes like 0, 1, 2 etc.
Consequently you can make your looping a lot simpler and just iterate over the object keys directly.
N.B. You also need to parse the data from JSON (i.e. a notation format in plain text) into a JavaScript variable before you can begin. Since you're using jQuery's $.ajax() you can set the dataType: "json" option which causes jQuery to process the response as JSON and parse it for you automatically before it provides the data to your callback.
I also fixed your template literal syntax - you need to use backticks (`) and the dollar sign to make it work.
Here's a runnable demo (using a dummy endpoint since yours doesn't support CORS):
$(document).ready(function f() {
$.ajax({
url: "https://api.myjson.com/bins/ntsyj",
dataType: "json"
}).done(function(data) {
$.each(data, function(key, val) {
console.log(key + " : " + val);
$(`#${key}`).val(val);
});
//setTimeout(f, 1000); // refresh the data at each second(data changes at each 1sec)
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="firstName" />
<input id="lastName" />
<input id="123" />

The response is a plain string so yo. firstly, you need to parse it using build-in JSON.parse() function and then you can iterate over it.
To use template literal, you should put your variable between ${ and }.
Please consider the code bellow:
$(document).ready(function f() {
$.ajax('http://soner.dev/test.txt', {
success: function(data, status, xhr) {
var parsedData = JSON.parse(data);
$.each(parsedData, function( key, val ) {
console.log(key + " : " + val);
alert(key + " : " + val);
$(`#${key}`).val(val);
});
setTimeout(f, 1000); // refresh the data at each second(data changes at each 1sec)
}
});
});

Related

AJAX - Extracting Info from JSON Object

I have data in a JSON object with the following format:
[{"Feature 1 Name":111,"Feature 2":111,"Feature 3":"stringforfeature3"}]
I've started to write some code to pull information from an API, but am not sure how to extract information (for instance, "stringforfeature3" if I somehow call "Feature 3") from the JSON object.
ajax: {
type: "GET",
url: '/api/apiname/info/moreinfo', //where i'm pulling info from
dataType: "JSON",
success: function(data, textStatus, jqXHR) {
return {
title: // Where I'd like to use the extracted information
};
}
},
Any advice would be greatly appreciated!
First of all, the response is an array, You need to get the first element like this
response = data[0];
Do you know each of the keys in advance? If yes,
{ title: response['Feature 3'] }
Else you can loop over response
for (var key in response) {
if (p.hasOwnProperty(key)) {
console.log(key + " -> " + response[key]);
}
}
You should be able to extract the data using square bracket notation:
success: function(data, textStatus, jqXHR) {
return {
title: data[0]['Feature 3']
};
}
You result is an array, so I used data[0] to get the first item of array, or {"Feature 1 Name":111,"Feature 2":111,"Feature 3":"stringforfeature3"}.
In JavaScript you can access the same variable either using object.variable or object['variable']. Since your variable name has spaces, you are left with second option - data[0]['Feature 3']. Your result will be stringforfeature3.

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

How to return only part of JSON object from REST API with JQuery

So I've been trying to figure out a way to return only a specific key-value pair from a REST API call using JQuery. The initial call I'm going off of is:
jQuery.ajax({
type: "GET",
url: "https://BASEURL/api/project-type/list-all",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function ()
{
$('#projectTypeListLoading').text("Loading...");
},
success: function (data, status, jqXHR)
{
var trHTML = "";
$.each(data, function (i, item)
{
trHTML += '<tr><td>' + item.Name + '</td><td>' + item.Code + '</td><td>'
+ item.Order + '</td><td>' + item.IsActive + '</td><td>' + item.Id + '</td></tr>';
});
$('#projectTypesTable').append(trHTML);
$('#projectTypeListLoading').html("DONE");
},
error: function (jqXHR, status)
{
$('#projectTypeListLoading').html("Error loading list");
}
});
With this I can get a list of JSON Objects from my REST API like so:
[{"Name":"Project Type 2","Code":"2","Order":2,"IsActive":true,"Id":"c497e4e8-16b4-44e2-b6ac-a9a2c392d9d4"},{"Name":"Project Type 3","Code":"3","Order":3,"IsActive":true,"Id":"6da2a240-2327-4260-a6df-f4bec25535c2"}]
I then use these in my Ajax success portion and stick them in a table. Works perfectly. However, what I would like to have happen is to ONLY get say the Name key-value pair part of the JSON Object as the Response from my REST API. Like so:
[{"Name":"Project Type 2"},{"Name":"Project Type 3"]
And then in my Success function use:
success: function (data, status, jqXHR)
{
var trHTML = "";
$.each(data, function (i, item)
{
trHTML += '<tr><td>' + item.Name + '</td></tr>';
});
$('#projectTypesTable').append(trHTML);
$('#projectTypeListLoading').html("DONE");
},
I could achieve this result in two different ways. I could:
Change my REST API call to 'https://BASEURL/api/project-type/name'. And call this and have the API only return the name. I don't want to do this because I have 20 different urls which already return all, I will not be making a separate URL to access each key-value individually for each of these.
Get all like in my initial example then just ignore every key-value pair that isn't 'Name'. This would do what I want but the point is there will be many hundreds of these calls going on. Each of these calls would return the full JSON object then I'd cut that down; that's a lot of unnecessary chatter. I'd rather be able to specify which key-value pair I want to reduce server load.
Any advice on how to achieve this? Thanks.
There's no easy answer to this with REST endpoints. This is the exact problem that GraphQL, Falcor, OData and a number of other libraries were created to assist with.

how to use returned list in ajax call from controller

i am using ajax call to store the data in to DB and controller is returning the list of commentObject.
how can i access this list in JSP?
my ajax call is:
function StoreCommentAndRefreshCommentList(e) {
var commentData = document.getElementById(ActualCommentTextId).value;
$.ajax({
type : 'POST',
url : 'CommentStoreAndRetrieve',
data : "commentData=" + commentData + "&ImageId=" + commetTextButtonId[1],
success : function(commentList) {
//alert('comments stored successfully');
//alert('comment data is...'+res.CommentDataDoc[0]);
},
error : function(e) {
alert('Error: ' + e);
}
});
}
please let me know how can i access list data here.
function StoreCommentAndRefreshCommentList(e) {
var commentData = document.getElementById(ActualCommentTextId).value;
$.ajax({
type : 'POST',
url : 'CommentStoreAndRetrieve',
data : "commentData=" + commentData + "&ImageId=" + commetTextButtonId[1],
dataType : "xml",
success : function(commentList) {
alert($(commentList).text());
},
error : function(e) {
alert('Error: ' + e);
}
});
}
You can f.e. create <input type='hidden' id='someId'/> in your JSP and then in your success function you can assign data like $("#someId").val(...);
Another idea would be create JS variable inside JSP by putting <script>var myVar = ""</script>. Then in your succes function you can refer to such 'global' variable. Althogh, I believe that usual assignment (myVar = response.yourList) wouldn't work for a response object (which is the case in your problem). The solution would be to create an array var arr = [] and then in for loop you can push some done into it.
I got the solution.
i did used $.each(res, function (key, val) to iterate one by and built the tags dynamically using val field. here key holds the index position and val holds the corresponding object. then i did accessed one by one field by val.filedname(which we did create for pojo).
Thanks everyone.

Return Only Specific Values From Ajax JSON call

I'm having trouble with filtering the returned data from an Ajax JSON call. Right now, it returns:
{"results":[{"text":"RoboChat: What is it like to feel?","username":"RoboChat","createdAt":"2014-06-04T20:01:15.268Z","updatedAt":"2014-06-04T20:01:15.268Z","objectId":"wG2cs1OnVY"},
I'm trying to get it to return only the "text" object, like this:
"RoboChat:What is it like to feel?"
Here is my code:
function fetch () {
$.ajax({
url:"https://api.parse.com/1/classes/chats",
type : 'GET',
dataType : 'JSON',
data : JSON.stringify({
}),
success:function(data) {
$('.messages').append("<li>" + (JSON.stringify(data)) + "</li>")
}
});
};
I've tried passing a filter to JSON.stringify, but with no success, I'm not even sure if that's the way to approach filtering the data. Any help would be much appreciated.Thanks!
You can't really change what a request returns, but you can of course use the resulting value in any way you want. Since the response contains multiple objects with text properties, you have to iterate them and extract the text:
success: function(data) {
var results = data.results;
results.forEach(function (result) {
$('.messages').append("<li>" + result.text + "</li>");
});
}
The returned JSON has a results property which is an array, you can iterate through the array and read the text property of each element:
$.each(data.results, function(index, element) {
console.log(element.text);
});
For creating a li element for each array's element, you can use the $.map utility function:
var li = $.map(data.results, function(element) {
return '<li>' + element.text + '</li>';
});
$('.messages').append(li);
try for, the data has an array named results, from wich you have to select the first like following:
success: function(data) {
var results = JSON.parse(data).results;
results.forEach(function (result) {
$('.messages').append("<li>" + data.results[0].text + "</li>");
});
}

Categories

Resources