Cannot Read JSON Array Within JSON Array Using jQuery $.getJSON - javascript

I cannot get the items of an JSON array within an JSON object. Here's what my JSON looks like:
[
{
"category":9,
"channels":[
{
"id":5,
"title":"MYTITLE",
"active":true,
"recent":true,
"image":"/arts/736c1ad4-2dbe-40a6-859d-8dba89c26ec2.jpg",
"recent_tracks":{
"vip":"https://api.xyzsite.com/recent_tracks/vip-3.json",
"free":"https://api.xyzsite.com/recent_tracks/free-3.json"
},
"additional_vip_channels":[
{
"channel_name":"vip-3a",
"recent_tracks_uri":"https://api.xyzsite.com/recent_tracks/vip-3a.json",
"streams":{
"320":"http://streams.xyzsite.com/api/914/320/stream",
"64":"http://streams.xyzsite.com/api/914/64/stream",
"192":"http://streams.xyzsite.com/api/914/192/stream"
}
}
],
"streams":{
"free":"http://streams.xyzsite.com/api/31/56/stream",
"free_56":"http://streams.xyzsite.com/api/31/56/stream",
"free_128":"http://streams.xyzsite.com/api/31/128/stream",
"320":"http://streams.xyzsite.com/api/33/320/stream",
"64":"http://streams.xyzsite.com/api/33/64/stream",
"192":"http://streams.xyzsite.com/api/33/192/stream"
}
},
I use the following code to get the values:
$.getJSON('https://api.xyzsite.com/channels.json', function(response) {
$.each(response, function (index, value) {
var catId = value.category;
$.each(value.channels, function (index, value) {
XYZApp.channels.push({
categoryId: catId,
id: value.id,
name: value.title,
image: value.image,
recent_tracks: {
vip: value.recent_tracks.vip,
free: value.recent_tracks.free
},
streams: {
free_128: value.streams.free_128,
member_320: value.streams["320"],
member_64: value.streams["64"],
member_192: value.streams["192"]
}
});
console.log(value.additional_vip_channels);
});
});
}).
then ...
I can get the values, but I cannot read the additional_vip_channels array within the .each jQuery function. I already tried:
value.additional_vip_channels.channel_name
value.additional_vip_channels[0].channel_name
value.additional_vip_channels["0"].channel_name
but none of them work.
And the log output is also here:
How can I get the channel_name and other data in additional_vip_channels?

I believe that you would want:
channels[0]['additional_vip_channels'][0]['channel_name']
Equally, this should work: (just a different way of selecting)
channels[0].additional_vip_channels[0].channel_name
Hope that helps and works :)

Related

jQuery each loop for json data by index

I have some json data that the id number will change, so instead of referencing it by ID number I would like to reference it by array index.
I am looking to alert the source which would be the image URL https://upload.wikimedia.org/wikipedia/commons/thumb/8/89/Chuck_Schumer_official_photo.jpg/240px-Chuck_Schumer_official_photo.jpg
This is a sample of the json data:
{
"batchcomplete":"",
"query":{
"normalized":[
{
"from":"Chuck_Schumer",
"to":"Chuck Schumer"
}
],
"pages":{
"326708":{
"pageid":326708,
"ns":0,
"title":"Chuck Schumer",
"thumbnail":{
"source":"https://upload.wikimedia.org/wikipedia/commons/thumb/8/89/Chuck_Schumer_official_photo.jpg/240px-Chuck_Schumer_official_photo.jpg",
"width":240,
"height":300
},
"pageimage":"Chuck_Schumer_official_photo.jpg"
}
}
}
}
This is my JavaScript attempt:
function processWikiData(wikiData){
$(wikiData.query).each(function(index, query_item) {
$(query_item.pages).each(function(index, page_item) {
// I was hoping to get the array's first index here but clearly this is wrong
$(page_item.[0]).each(function(index, wiki_id) {
$(wiki_id.thumbnail).each(function(index, thumbnail_item) {
alert(thumbnail_item.source);
});
});
});
});
}

Selectize.js get more data in "onItemAdd" callback

TL;DR
To make it clearer, I want to have access to ALL the data in the selected JSON object inside the onItemAdd function. Right now I only have access to _id and name via the config variables.
Ok, so I have a working Selectize.js function grabbing a JSON object from my server and creating the select options.
What I want to know is, can I get anymore data from the existing JSON object inside the "onItemSelect" callback?
The only data I can get directly is the value as specified in the config, which in this case is the "_id" and the $item which i assume is form the labelField in the config, in this case is the name form the JSON data.
How can I get more data than that for the selected item? You see in the render object I use the variable item.sku, how can I access the sku variable in the "onItemAdd" callback?
the data form the server is a json array:
[
{ _id: 'abcd1234', name: 'Sample', sku: '00123' },
{ _id: 'efgh5678', name: 'Sample2', sku: '00124' }
]
My function
// setup select box to add new products to list
$('#buyingGroupAddProducts').selectize({
valueField: '_id',
labelField: 'name',
searchField: 'name',
options: [],
create: false,
closeAfterSelect: true,
render: {
option: function(item, escape) {
return '<div>'+ escape(item.sku) + ': ' + escape(item.name) + '</div>';
}
},
load: function(query, callback) {
if (!query.length) return callback();
$.ajax({
url: '/buying/products-search',
type: 'GET',
dataType: 'json',
data: {
q: query
},
error: function() {
callback();
},
success: function(res) {
callback(res);
}
});
},
onItemAdd: function(value, $item) {
// DO the thing
console.log($item);
}
});
SelectizeJS site: http://selectize.github.io/selectize.js/
a hack to solve your problem : inside onItemAdd function you can access all your JSON : this.options gives you all the selectize options, so now you have the value and the complete JSON, you can easily find back the item in your json that corresponds to the value selected. I can complete my answer if you provide a use case in plunker.

Algolia filter by nested attribute JavaScript

So I am using Algolia.com to index users for quick searching.
An example object in index:
{
id: 1,
username: "john.doe",
name: "John Doe",
attributes: {
gender: "male",
hair_color: "blonde",
eye_color: "blue",
height: 165
}
}
I'd like to filter results by a specific attribute (object key) in the attributes object.
I thought maybe using facetFilters would do the job, but I am unable to get it working.
I have tried many variances of this code:
user_index.search('', {
facets: '*',
facetFilters: ['attributes.hair_color:blonde', 'attributes.eye_color:blue']
}, function(error, data) {
console.log(error, data);
});
-- / --
user_index.search('', {
facets: '*',
facetFilters: ['hair_color:blonde']
}, function(error, data) {
console.log(error, data);
});
Please find the documentation here: https://www.algolia.com/doc/javascript
Just in order to be able to mark this question as answered :
You should add attributes.hair_color to your attributesForFaceting (Display tab in your index dashboard)
You should be able to easily just do
user_index.search('', {
facetFilters: 'attributes.hair_color:blonde'
}, function () {
console.log(arguments);
});
to search.
Sounds like using facet filters is the best way to achieve what you're looking for. The easiest way is to handle those filters is probably to use the Javascript Helper https://github.com/algolia/algoliasearch-helper-js#filtering-results.
You would then only need to call
helper.addFacetRefinement('hair_color', 'blonde').search();

Adding keys to objects in a parse object

Im working with the parse javascript sdk and i want to add a key to an object in a Parse 'object' when saving it.
For ex:
var saveGif = new SaveGifTags();
saveGif.save({
type: req.body.type,
tag: req.body.tags[i],
gifObjects: newGif
}, {
success: function(data) {
console.log(data);
res.json(data);
},
error: function(data) {
console.log(data);
}
});
gifObjects is my object in the Parse Class. I tried to do something like this
gifObjects: gifOjects[gifObj.id] = newGif;
newGif of course is the object i want to save. This gave me an error of gifObjects is not defined. So i tried something like this
gifObjects[gifObj.id] : newGif;
that didnt work either. i want to create something like this:
{
hgs32: {
url: '',
image: ''
},
64522 : {
url: '',
image: ''
}
}
any suggestions?
Figured it out. Not sure what the downvote is for, but i had to create the object before i saved it.
var gifObjects = {};
gifObjects[gifObj.id] = newGif;
and then the save
saveGif.save({
type: req.body.type,
tag: req.body.tags[i],
gifObjects: gifObjects
},

Can't get select2 to work with a json file

I am trying to get select2 to work with an external json-file:
The json-file looks like this (it is called data.json and is in the root directory of my Website):
{"laender":[
{
"Land" : "Ägypten",
"kurz" : "EG",
"Fahne" : "aegypten"
},
{
"Land" : "Andorra",
"kurz" : "AN",
"Fahne" : "andorra"
}
]}
The Javascript Looks like this:
$(document).ready(function($) {
function formatValues(data) {
return data.Land + ' ' + data.Fahne;
}
$('#countrySelect').select2({
ajax: {
dataType: "json",
url: "data.json",
results: function (data) {
return {results: data};
}
},
formatResult: formatValues
});
(As mentioned here: Select2 load data with Ajax from file).
The Output in HTML is a simple
<div id="countrySelect"></div>
But I can't get it to work. I tried so many things but nothing happens. Also I am rather new to json and Ajax.
Thanks for any help in advance!
Dietmar
your javascript code is for old version select2 below 4.0.0. if you using select2 4.0.0, then you must using processResult instead of result.
try to change these lines
results: function (data) {
return {results: data};
}
to like this
processResults: function (data) {
return {results: data};
}
for additional info, select2 4.0.0 doesn't support input hidden anymore. so, your #countrySelect must be select element rather than hidden input.
sorry my bad english
reference:
select2 4.0.0 ajax documentation
Your keys in json is:
"Land", "kurz", "Fahne",
but select2 in this case expect:
"id", "text"
to make: <option value="id"> text </option>
You should use map function:
processResults: function(data){
return {
results: $.map(data, function(smthg){
return { id: smthg.kurz, text: smthg.Fahne }
})
};
}
its example, i don't know which values You want use, and i use json like:
[
{"id_pr":"1252","pr":"aaa"},
{"id_pr":"1253","pr":"bbb"}
...
]
and it works, but
i didn't try:
{ laender: [
{"id_pr":"1252","pr":"aaa"},
{"id_pr":"1253","pr":"bbb"}
]}

Categories