json variable is undefined - javascript

I have a json file in a folder called json/img_desc.json
Here is the json file
{ "theimages":[
{
"number":1,
"title":"Joy Toy teddy bear",
"description":"In etc etc"
} etc etc
Then I used this code to try and get the first value.
$.getJSON('json/img_desc.json', function(theimages) {
console.log(img_desc.theimages.number[0]);
});
The error
It says this
[15:06:46.951] ReferenceError: img_desc is not defined #
file:///[removed for privacy]/js/puzzle.js:246

it should be
$.getJSON('json/img_desc.json', function (theimages) {
console.log(theimages.theimages[0].number);
//if you want to loop
$.each(theimages.theimages, function (idx, obj) {
console.log(obj.number)
})
});

Documentation says http://api.jquery.com/jQuery.getJSON/#jQuery-getJSON-url-data-success-data--textStatus--jqXHR- it will pass a plain object as the second parameter. So, you can do something like this
$.getJSON('json/img_desc.json', function(theimages) {
$.each(theimages.theimages, function( index, val ) {
console.log(val, val.number);
});
});

$.getJSON('json/img_desc.json', function(img_desc) {
console.log(img_desc.theimages.number[0]);
});
Should fix your problem. As if you have any other problem, ask it in a separate question.

Related

Vue js : Filter dynamic data

In my Vuejs below I want to filter the reviewed:true only questions, and get the length of them, but my code below gives an error TypeError: question.reviewed.includes is not a function ,is there a way to do it?
Here is the screenshot about the json file:
JSON File
filterReviewed() {
return this.questions.filter((question) => {
return (
question.reviewed
.includes('true')
);
});
},
includes is a method of Object of Array type. Directly judge attribute reviewed is OK
filterReviewed (){
return this.questions.filter((question) => question.reviewed);
}
To filter the reviews try this:
filterReviewed() {
return this.questions.filter((question) => question.reviewed === true);
},
To get the filterReviewed length try this:
filterReviewed.questions.length

Access JSON Array with Javascript?

I get an JSON array via an Ajax request. This one looks like this:
{
"data":{
"title":"Frau",
"academic_title":null,
"first_name":"Lynda",
"last_name":"McCrow",
"company":"Tekfly",
"street":"Sage",
"zip":"4860-077",
"country":"Portugal",
"city":"Quinta",
"phone":"6727086107",
"fax":"4941912651",
"mobile":"3722716317",
"email":"lmccrow7#newyorker.com",
"web":"shop-pro.jp",
"mailbox":"81-0982335",
"mailbox_country":"Indonesia",
"mailbox_zip":null,
"mailbox_city":"Susoh",
"birthday":"1977-02-11"
}
}
But I have no idea, how to access the JSON array. I already tried all of this:
success: function(data) {
console.log(data[0].data.title);
console.log(data[0].title);
console.log(data.data[0].title);
console.log(data.title);
}
Can you guys give me a hint?
Kind regards
You have tried everything except:
data.data.title
It's an Object and you need to use Object.key() or something to iterate. Technically, it's like this:
// Inside your function, this is what gets passed.
data = {
"data":{
"title":"Frau",
"academic_title":null,
"first_name":"Lynda",
"last_name":"McCrow",
"company":"Tekfly",
"street":"Sage",
"zip":"4860-077",
"country":"Portugal",
"city":"Quinta",
"phone":"6727086107",
"fax":"4941912651",
"mobile":"3722716317",
"email":"lmccrow7#newyorker.com",
"web":"shop-pro.jp",
"mailbox":"81-0982335",
"mailbox_country":"Indonesia",
"mailbox_zip":null,
"mailbox_city":"Susoh",
"birthday":"1977-02-11"
}
};
for (var key in data.data) {
console.log(`${key}: ${data.data[key]}`);
}
data is not an array, nor JSON, it's an object literal. Your last try comes close, but you need to access
data.data.title
or you could destructure data in the success param
success: function({data}) {
// now you could access data.title directly
console.log(data.title);
}

Word add-in: Get whole document but File.getSliceAsync method not returning

I'm creating an Office Add-in and am having trouble with the javascript file.getFileAsync method in Word Online (Word 2013 desktop is fine).
I'm using sample code from github...
https://github.com/OfficeDev/office-js-docs/blob/master/docs/word/get-the-whole-document-from-an-add-in-for-powerpoint-or-word.md
My code looks like this...
function getFile() {
Office.context.document.getFileAsync(Office.FileType.Text,
{ sliceSize: 65536},
function (result) {
if (result.status == Office.AsyncResultStatus.Succeeded) {
// Get the File object from the result.
var myFile = result.value;
var state = {
file: myFile,
counter: 0,
sliceCount: myFile.sliceCount
};
getSlice(state);
}
});
}
function getSlice(state) {
state.file.getSliceAsync(state.counter, function (result) {
if (result.status == Office.AsyncResultStatus.Succeeded) {
sendSlice(result.value, state);
state.file.closeAsync();
}
else if(result.status == 'failed')
state.file.closeAsync();
});
}
Before calling file.getSliceAsync the data looks good - myFile.sliceCount is 1. The result function is never called and no errors are thrown in the console.
Thanks for any help you can provide!
UPDATE: this issue is fixed and live. Please try it again it must work now.
thanks!
---------------- ORIGINAL ANSWER JUST FOR REFERENCE ----------------------------
Yes, there is a regression right now in Word Online preventing the code to run successfully. The specific issue is that the file.getSliceAsync method is never calling the call-back function. This only happens with the TEXT type, if you want to get the docx or pdf this should work ok. This issue will be fixed in a couple of weeks.
You have an alternative if you want to get the text of the document you can use the new APIs for Word check out this sample:
Word.run(function(context) {
var myBody = context.document.body;
context.load(myBody);
return context.sync()
.then(function(){
console.log(myBody.text);
});
});
Hope this helps!
Thanks for reporting this issue!
Juan.

How to read from JSON in protractor test?

I would like to read groups_id_ss for specific id.
How to do that in this json?
I successfully read response.docs , but then can't reach id and groups_id_ss.
{
"responseHeader":{
"status":0,
"QTime":0,
"params":{
"q":"object_type_s:USER",
"indent":"true",
"wt":"json"
}
},
"response":{
"numFound":13,
"start":0,
"docs":[
{
"id":"sanja",
"groups_id_ss":[
"COORDINATION AO",
"ACM_INVESTIGATOR_DEV"
]
},
{
"id":"sanjaseconduser",
"groups_id_ss":[
"ACM_SUPERVISOR_DEV",
"CHAIRMAN",
"ACM_ADMINISTRATOR_DEV",
"CPC INITIATOR",
"COORDINATION AO",
"ACM_INVESTIGATOR_DEV"
]
}
]
}
}
As stated you could read response.docs from json. Let's say
var docs = response.docs;
As docs is an array you can use forEach to loop thruogh each element
docs.forEach(function(doc) {
if(doc.id === "desired_Id") {
var groupIdSS = doc.groups_id_ss;
}
});
This way you can read groups_id_ss for desired id.
Hope it helps.
Since you are using the values in separate file, you can use like this.
I am assuming the file is stored as .json
For example, your json values are in response.json
You can write code like this in your spec file:
var responseData = require('../../response.json');
describe('some function description', function(){
var groupID = responseData.response.docs[0].groupid_ss[0];
var groupID = responseData.response.docs[0].groupid_ss[0]
});
Since that is json array, we have to give the index of the array in that.
Hope this would work for you.

How to check for json results before passing on?

i have this function to retrieve json data from yql query
function link(b){
var jsonURI = "http://query.yahooapis.com/v1/public/yql?q="+encodeURIComponent("select href,alt,content from html where url='"+b+"' and xpath='//a[#id=\"download\"] |//img[#class=\"dvLinkOverlayFill\"] |//meta[#name=\"title\"]'")+"&format=json&diagnostics=true&_maxage=86400&callback=callback&jsoncallback=?";
jQuery.ajaxSetup({cache: true});
jQuery.getJSON(jsonURI,callback);
}
What i want is to check if the data is null or not before passing on to the callback, if its null, it runs again the link() function, if not it passes on, i have tried
if (jQuery.query.results == null){link(b);}
but no luck, any advice or guide?
EDIT: Got it working, part of it, by using
if (o.query.results == null) { link(b); }
inside the callback function
callback(o){
if (o.query.results == null) { link(b); }
However i can't pass the "b" from the link function to the callback function, it's the only thing that is left for this to work, something like callback(o,b) that could be passed on in here jQuery.getJSON(jsonURI,callback);
since this one is sending the "o", how to make it send the "b" aswell? something like
jQuery.getJSON(jsonURI,callback(o,b));
EDIT updated question answer:
function link(b){
var jsonURI = "http://query.yahooapis.com/v1/public/yql?q="+encodeURIComponent("select href,alt,content from html where url='"+b+"' and xpath='//a[#id=\"download\"] |//img[#class=\"dvLinkOverlayFill\"] |//meta[#name=\"title\"]'")+"&format=json&diagnostics=true&_maxage=86400&callback=callback&jsoncallback=?";
jQuery.ajaxSetup({cache: true});
jQuery.getJSON(jsonURI,function(data, status, xhr){
callback(data, status, xhr,b);
});
}
So you got ur b object in arguments[3]
Couldn't you just simplify that?
if (!jQuery.query.results) { link(b); }

Categories

Resources