How do I access an object in json? - javascript

I have a json structured like this:
{
"total": 4367,
"page": 1,
"per_page": 10,
"paging": {
"next": "/videos?query=second%20world%20war&per_page=10&access_token=XXX&page=2",
"previous": null,
"first": "/videos?query=second%20world%20war&per_page=10&access_token=XXX&page=1",
"last": "/videos?query=second%20world%20war&per_page=10&access_token=XXX&page=437"
},
"data": [
{
"uri": "/videos/128373915",
"name": "The Fallen of World War II",
I need to access name and I tried:
$.ajax( {
type: "GET",
url: url,
dataType: 'json',
success: vimeoResultsFunc
});
function vimeoResultsFunc(data){
for (var i = 0; i < data.length; i++) {
console.log(data[i].name);
}
}
But i get nothing

You're missing a level there. The vimeoResultsFunc will receive the top level object, then you have an array called data. Based on what you have it should be
function vimeoResultsFunc(data){
for (var i = 0; i < data.data.length; i++) {
console.log(data.data[i].name);
}
}

In the function vimeoResultsFunc(data) just add console.log(data) and see what is inside the data object. Probably this object does not have the structure you expect.

Related

Combine result from 2 api response into one array javascript

I have two different api response that I want to combine. First api response is like below
"Data1":[
{
"name": "First Officer",
"status": "ACTIVE",
"id": "111"
},
{
"name": "Second Officer",
"status": "DELETED",
"id": "222"
},
{
"name": "Third Officer",
"status": "ACTIVE",
"id": "333"
}
],
Data2[],
Data3[]
And the second response is to get latest position of the officer like below
[
{
"id": "111",
"latest_position": "Elm Street"
},
{
"id": "333",
"latest_position": "Newton Sr. Street"
}
]
I need to combine two response from API above to become one array like this
["111","First Officer","Elm Street"]
["333", "Third Officer","Newton Sr. Street"]
But what I get is data like
["333","Third Officer","Elm Street"]
["333", "Third Officer","Newton Sr. Street"]
Do you know where's the error from my code below
$.ajax({
url: api_url+'search?keyword='+keyword,
type: 'GET',
success: function(response) {
//console.log(response);
var keys = Object.keys(response.data);
for (var i = 0; i < keys.length; i++) {
var data = response.data[keys[i]]
for (var j = 0; j < data.length; j++) {
var name = data[j].name;
var sid = data[j].id;
$.ajax({
url: api_url+'positions?filter=%7B%22where%22%3A%7B%22user_id'+sid,
type: 'GET',
success: function(response2) {
//console.log(response);
for (var i = 0; i < response2.length; i++) {
var loc = response2[i].latest_position;
var obj = {
'id' : sid,
'name' : name,
'loc' : loc,
};
arrObj.push(obj);
}
}
})
}
}
console.log(arrObj);
Thank you
You can use Array.find to search the item from the second response by id.
Something like this:
const response1 = [{
"name": "First Officer",
"status": "ACTIVE",
"id": "111"
},
{
"name": "Second Officer",
"status": "DELETED",
"id": "222"
},
{
"name": "Third Officer",
"status": "ACTIVE",
"id": "333"
}
];
const response2 = [{
"id": "111",
"latest_position": "Elm Street"
},
{
"id": "333",
"latest_position": "Newton Sr. Street"
}
];
const merged = response2.map(item => {
const resp1Item = response1.find(r => r.id === item.id);
return { ...item,
...resp1Item
}
});
console.log(merged);
Your issue stems from the fact that the second $.ajax(...) call is asynchronous and by the time its success: callback gets to be evaluated, the fors are finished, so you're getting the last values from the arrays in all of the responses.
The solution is to create a closure around the second $.ajax(....) call, so it will make the definition context available at execution time.
Something around the lines of:
$.ajax({
url: api_url+'search?keyword='+keyword,
type: 'GET',
success: function(response) {
//console.log(response);
var keys = Object.keys(response.data);
for (var i = 0; i < keys.length; i++) {
var data = response.data[keys[i]]
for (var j = 0; j < data.length; j++) {
(function(data){
var name = data.name;
var sid = data.id;
$.ajax({
url: api_url+'positions?filter=%7B%22where%22%3A%7B%22user_id'+sid,
type: 'GET',
success: function(response2) {
//console.log(response);
for (var i = 0; i < response2.length; i++) {
var loc = response2[i].latest_position;
var obj = {
'id' : sid,
'name' : name,
'loc' : loc,
};
arrObj.push(obj);
}
}
})
})(data[j]);
}
}
console.log(arrObj);

Javascript .getJSON multiple URLs

I have WEbDataconnector in Javascript, which download data from .json file and load table:
myConnector.getData = function(table, doneCallback) {
$.getJSON("http://url/api/opls/number/tasks?apiKey", function(resp) {
var feat = resp.data,
tableData = [];
// Iterate over the JSON object
var keys = Object.keys(feat);
for (var i = 0, len = keys.length; i < len; i++) {
tableData.push({
"taskId": feat[keys[i]].taskId,
"owner": feat[keys[i]].owner,
"description": feat[keys[i]].description,
"responsible": feat[keys[i]].responsible,
});
}
table.appendRows(tableData);
doneCallback();
});
My problem is that i have multiple URL, with different numbers and apikeys. And i need combine data from all URLs into one table.
Could anyone please help me out? Thank you.
edit:
If i add more elements to data.push() method it ends with:"null is not an object" because some objects in JSON are null,
example of JSON:
"1026533": {
"taskId": 1026533,
"opl": 6919,
"owner": "name",
"description": "text",
"responsible": "name",
"taskStart": {
"date": "2016-03-21 13:28:11.000000",
"timezone_type": 3,
"timezone": "Europe\/Prague"
but sometimes there is an element taskStart with null:
"1026535": {
"taskId": 1026535,
"opl": 6919,
"owner": "name",
"description": "text",
"responsible": "name",
"taskStart": null,
how can i check this and push all data or null? thank you
Use recursion and named function expression with a list of URL.
myConnector.getData = function (table, doneCallback) {
var urls = [ /* the urls */]
if (urls.length == 0) return doneCallback();
$.getJSON(urls.shift(), function callback(resp) {
var feat = resp.data,
tableData = [];
// Iterate over the JSON object
var keys = Object.keys(feat);
for (var i = 0, len = keys.length; i < len; i++) {
tableData.push({
"taskId": feat[keys[i]].taskId,
"owner": feat[keys[i]].owner,
"description": feat[keys[i]].description,
"responsible": feat[keys[i]].responsible,
});
}
table.appendRows(tableData);
var url = urls.shift();
if (url) return $.getJSON(url, callback); // recursion happens here
doneCallback();
});
}
Keep an array containing all the urls that you need to fetchs.
urls = [
'http://url/api/opls/number1/tasks?apiKey1',
'http://url/api/opls/number2/tasks?apiKey2',
'http://url/api/opls/number3/tasks?apiKey3'
];
Then iterate over the array and send an ajax request on each url.
urls.forEach(function(url) {
$.getJSON(url, function(resp) {
var feat = resp.data,
let data = [];
// Iterate over the JSON object
var keys = Object.keys(feat);
for (var i = 0, len = keys.length; i < len; i++) {
data.push({
"taskId": feat[keys[i]].taskId,
"owner": feat[keys[i]].owner,
"description": feat[keys[i]].description,
"responsible": feat[keys[i]].responsible,
});
}
table.appendRows(data);
doneCallback();
});
});

Unable to bind json data (api result) to dropdown using jquery/js in MVC

I want to bind json data returned by API to dropdownlist.
but unable to fetch value id and name.
Json Format :
{
"categories": [
{
"categories": {
"id": 1,
"name": "CatOne"
}
},
{
"categories": {
"id": 2,
"name": "CatTwo"
}
}
]
}
I am returning JsonResult, using
return Json(responseData, JsonRequestBehavior.AllowGet);
and in Jquery call ,I am using
$.ajax({
type: "POST",
url: "/Home/City",
contentType: "application/json; charset=utf-8",
global: false,
async: false,
dataType: "json",
success: function (jsonObj) {
var listItems = "";
//here I want to get id and name
});
}
});
You can populate dropdown from your json like following.
var json = {
"categories": [
{ "categories": { "id": 1, "name": "CatOne" } },
{ "categories": { "id": 2, "name": "CatTwo" } }
]
}
$.each(json.categories, function () {
$('select').append('<option value="' + this.categories.id + '">' + this.categories.name + '</option>')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select></select>
You can just stick a break point (or debugger; statement) inside your success callback. Then you can inspect your jsonObj and it'll tell you exactly what you need to know.
In this case, you should be able to iterate on jsonObj.categories, and your id and name properties will be accessible via jsonObject.categories[i].categories.id and jsonObject.categories[i].categories.name
So your success method will look something like:
for(var i = 0; i < jsonObj.categories.length; i++) {
var category = jsonObj.categories[i].categories;
var id = category.id;
var name = category.name;
}
I would also suggest formatting your json differently, as other answers have suggested.

C# ListItemCollection to JSON, while keeping values and text items

I have created a web service (asmx file) that returns a serialized ListItemCollection with the following code.
public string getStates(string Country)
{
ListItemCollection lic = DBInterface.GetStates(Country);
var serialized = JsonConvert.SerializeObject(lic);
return serialized;
}
I call the web service via javascript when a user selects a country from a dropdown list using the following code.
//ajax function that uses web services to get states
function GetStates(val)
{
$.ajax({
type: "POST",
url: "/WebServices/getServerData.asmx/getStates",
data: JSON.stringify({Country: val}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#ddlState").empty();
var parsed = JSON.parse(data.d);
for (var i = 0; i < parsed.length; i++) {
$("#ddlState").append("<option value='" + parsed[i] + "'>" + parsed[i] + "</option>");
}
},
error: function (data) {
alert(data.status + " " + data.statusText);
}
});
}
The issue is that I want to also keep not only the ListItemCollection text, but also it's value. However the "JsonConvert.SerializeObject only returns the text items. Can someone help to return the value and text so that I can populate the dropdown via javascript?
Thanks!
One thing you can use the JavaScriptSerializer() in System.Web.Script.Serialization:
ListItemCollection lic = new ListItemCollection() {
new ListItem("Display Text", "val1"),
new ListItem("Display Text 2", "val2"),
};
var ser = new JavaScriptSerializer();
var serialized = ser.Serialize(lic);
Results in (I took the liberty to format) :
[
{
"Attributes": {
"Keys": [],
"Count": 0,
"CssStyle": {
"Keys": [],
"Count": 0,
"Value": null
}
},
"Enabled": true,
"Selected": false,
"Text": "Display Text",
"Value": "val1"
},
{
"Attributes": {
"Keys": [],
"Count": 0,
"CssStyle": {
"Keys": [],
"Count": 0,
"Value": null
}
},
"Enabled": true,
"Selected": false,
"Text": "Display Text 2",
"Value": "val2"
}
]

Convert JSON Object to a simple array [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I have the following nested JSON Object coming from this call:
var jsonData = jQuery.ajax({
url: "http://testsite/_vti_bin/listdata.svc/ProjectHours",
dataType: "json",
async: false
}).responseText;
{
"d": {
"results": [
{
"__metadata": {
"uri": "http://testsite/_vti_bin/listdata.svc/ProjectHours(1)",
"etag": "W/\"1\"",
"type": "Microsoft.SharePoint.DataService.ProjectHoursItem"
},
"ContentTypeID": "0x0100C5D130A92A732D4C9E8489B50657505B",
"Title": "Ryan Cruz",
"Hours": 35,
"Id": 1,
"ContentType": "Item",
"Modified": "/Date(1373535682000)/",
"Created": "/Date(1373535682000)/",
"CreatedBy": {
"__deferred": {
"uri": "http://testsite/_vti_bin/listdata.svc/ProjectHours(1)/CreatedBy"
}
},
"CreatedById": 19,
"ModifiedBy": {
"__deferred": {
"uri": "http://testsite/_vti_bin/listdata.svc/ProjectHours(1)/ModifiedBy"
}
},
"ModifiedById": 19,
"Owshiddenversion": 1,
"Version": "1.0",
"Attachments": {
"__deferred": {
"uri": "http://testsite/_vti_bin/listdata.svc/ProjectHours(1)/Attachments"
}
},
"Path": "/sites/itg/Resourcecenters/spwidgets/Lists/ProjectHours"
},
{
"__metadata": {
"uri": "http://testsite/_vti_bin/listdata.svc/ProjectHours(2)",
"etag": "W/\"1\"",
"type": "Microsoft.SharePoint.DataService.ProjectHoursItem"
},
"ContentTypeID": "0x0100C5D130A92A732D4C9E8489B50657505B",
"Title": "Phillip Phillips",
"Hours": 25,
"Id": 2,
"ContentType": "Item",
"Modified": "/Date(1373535694000)/",
"Created": "/Date(1373535694000)/",
"CreatedBy": {
"__deferred": {
"uri": "http://testsite/_vti_bin/listdata.svc/ProjectHours(2)/CreatedBy"
}
},
"CreatedById": 19,
"ModifiedBy": {
"__deferred": {
"uri": "http://testsite/_vti_bin/listdata.svc/ProjectHours(2)/ModifiedBy"
}
},
"ModifiedById": 19,
"Owshiddenversion": 1,
"Version": "1.0",
"Attachments": {
"__deferred": {
"uri": "http://testsite/_vti_bin/listdata.svc/ProjectHours(2)/Attachments"
}
},
"Path": "/sites/itg/Resourcecenters/spwidgets/Lists/ProjectHours"
}
]
}
}
I want to loop through each object's Title and Hours attribute and save them in an array so I can pass it to the google chart as below:
var data = google.visualization.arrayToDataTable(array);
I tried the following code, but it can't find the json object:
function drawTable() {
var jsonData = jQuery.ajax({
url: "http://testsite/_vti_bin/listdata.svc/ProjectHours",
dataType: "json",
async: false
}).responseText;
alert(jsonData);
var obj = jQuery.parseJSON(jsonData);
//alert(jsonData.length);
var sampleData = [], results = d.results;
for (var i = 0, len = results.length; i < len; i++) {
var result = results[i];
sampleData.push({ Title: result.Title, Hours: result.Hours});
}
var data = google.visualization.arrayToDataTable(obj);
var chart = new google.visualization.PieChart(document.getElementById('spChart'));
chart.draw(data, {showRowNumber: true});
}
Please give me some ideas so i don't get stuck here for the rest of the day. Thank you!
jQuery.getJSON({"http://testsite/_vti_bin/listdata.svc/ProjectHours",{},function(d) {
var sampleData = [], results = d.results;
for (var i = 0, len = results.length; i < len; i++) {
var result = results[i];
sampleData.push({ Title: results[i].Title, Hours: results[i].Hours});
};
});
OK, I am answering my own question here in case someone runs across something similar.
This was an ajax call to a MS SharePoint site returning list data in JSON.
jQuery.ajax({
url: "http://testsite/_vti_bin/listdata.svc/ProjectHours",
dataType: 'JSON',
success:function(data) {
//jQuery('#spChart').append(JSON.stringify(json));
//var obj = jQuery.parseJSON(data);
var rowArray = [], results = data.d.results;
for (var i=0; i < results.length; i++)
{
var result = results[i];
rowArray.push([result.Title, result.Hours]);
//rowArray.push(["'" + result.Title + "'", result.Hours]);
}
},
error:function(){
alert("Error");
}
});
I had to first refer the json being returned as 'data' and access each javascript object inside of it as data.d.results[0], data.d.results[1], data.d.results[2] etc by looping through each of them.

Categories

Resources