How we can get value of json code in jquery - json

I send data using ajax and return json code.How can I get each Name key's value. Below is my code :-
[{"Name":"Calendar","EmailTemplates":[],
"Href":"http://amt-ars-d.sevenverbs.com/api/v1/emailtemplategroups/1"},
{"Name":"Products","EmailTemplates":[],
"Href":"http://amt-ars-d.sevenverbs.com/api/v1/emailtemplategroups/2"},
{"Name":"Personal Events","EmailTemplates":[],
"Href":"http://amt-ars-d.sevenverbs.com/api/v1/emailtemplategroups/3"},
{"Name":"Health Tips","EmailTemplates":[],"Href":"http://amt-ars-d.sevenverbs.com/api/v1/emailtemplategroups/4"},
{"Name":"Financial Tips ","EmailTemplates":[],"Href":"http://amt-ars-d.sevenverbs.com/api/v1/emailtemplategroups/5"}]
I want this output :
calender
Procudt

Try this,
var x = eval(YourJsonInput);
for(var i=0; i<x.length; i++)
{
var name = x[i].Name; //Here you get the name
var link = x[i].Href; //Here you get the href
}

Related

XmlService.parse() not able to handle HTML tables

I am looking for help from this community regarding the below issue.
// I am searching my Gmail inbox for a specific email
function getWeeklyEmail() {
var emailFilter = 'newer_than:7d AND label:inbox AND "Report: Launchpad filter"';
var threads = GmailApp.search(emailFilter, 0, 5);
var messages=[];
threads.forEach(function(threads)
{
messages.push(threads.getMessages()[0]);
});
return messages;
}
// Trying to parse the HTML table contained within the email
function getParsedMsg() {
var messages = getWeeklyEmail();
var msgbody = messages[0].getBody();
var doc = XmlService.parse(msgbody);
var html = doc.getRootElement();
var tables = doc.getDescendants();
var templ = HtmlService.createTemplateFromFile('Messages1');
templ.tables = [];
return templ.evaluate();
}
The debugger crashes when I try to step over the XmlService.parse function. The msgbody of the email contains both text and HTML formatted table. I am getting the following error: TypeError: Cannot read property 'getBody' of undefined (line 19, file "Code")
If I remove the getParsedMsg function and instead just display the content of the email, I get the email body along with the element tags etc in html format.
Workaround
Hi ! The issue you are experiencing is due to (as you previously mentioned) XmlService only recognising canonical XML rather than HTML. One possible workaround to solve this issue is to search in the string you are obtaining with getBody() for your desired tags.
In your case your main issue is var doc = XmlService.parse(msgbody);. To solve it you could iterate through the whole string looking for the table tags you need using Javascript search method. Here is an example piece of code retrieving an email with a single table:
function getWeeklyEmail() {
var emailFilter = 'newer_than:7d AND label:inbox AND "Report: Launchpad filter"';
var threads = GmailApp.search(emailFilter, 0, 5);
var messages=[];
threads.forEach(function(threads)
{
messages.push(threads.getMessages()[0]);
});
return messages;
}
// Trying to parse the HTML table contained within the email
function getParsedMsg() {
var messages = getWeeklyEmail();
var msgbody = messages[0].getBody();
var indexOrigin = msgbody.search('<table');
var indexEnd = msgbody.search('</table');
// Get what is in between those indexes of the string.
// I am adding 8 as it indexEnd only gets the first index of </table
// i.e the one before <
var Table = msgbody.substring(indexOrigin,indexEnd+8);
Logger.log(Table);
}
If you are looking for more than one table in your message, you can change getParsedMsg to the following:
function getParsedMsg() {
// If you are not sure about how many you would be expecting, use an approximate number
var totalTables = 2;
var messages = getWeeklyEmail();
var msgbody = messages[0].getBody();
var indexOrigin = msgbody.indexOf('<table');
var indexEnd = msgbody.indexOf('</table');
var Table = []
for(i=0;i<totalTables;i++){
// go over each stable and store their strings in elements of an array
var start = msgbody.indexOf('<table', (indexOrigin + i))
var end = msgbody.indexOf('</table', (indexEnd + i))
Table.push(msgbody.substring(start,end+8));
}
Logger.log(Table);
}
This will let you store each table in an element of an array. If you want to use these you would just need to retrieve the elements of this array and use them accordingly (for exaple to use them as HTML tables.
I hope this has helped you. Let me know if you need anything else or if you did not understood something. :)

JSON Query in Google Sheets/Scripts

I am importing data from a JSON file using Google Apps Script and Google Sheets. I have learned the basics on this, but the formatting on the JSON file I am attempting to parse is throwing me off.
What is confusing me is how I would search for information based on "name". Currently I am using this:
function JSONReq(url, xpath){
var res = UrlFetchApp.fetch(url);
var content = res.getContentText();
var json = JSON.parse(content);
var patharray = xpath.split("/");
for(var i = 0; i < patharray.length; i++){
json = json[patharray[i]];
}
return json;
}
I'm a bit lost now to be honest with you.
I want to have a cell where I can type a name that I already know of, then find it in the JSON file and pull the return that information however I decide to do it. I can pull and write to cells, I have the basics down. But I just can't understand how I could search by the name.
That JSON file is an array of objects. To find a specific object with a given "name", you would parse it into an object (which you do already), then iterate through them and check the name parameter:
var myName = "name of thing I want";
var arr = JSON.parse( ... );
for(var i = 0; i < arr.length; ++i) {
var obj = arr[i];
if(obj.name == myName) { // could be done as obj["name"] == ... too
// do stuff with obj
}
}
For your case, you might add an additional argument to your function (i.e. 2nd arg = the object's property, e.g. "name", with the 3rd = the desired value. This will be fine for any simple key-value properties, but would need specific handling for where the value is itself an object (e.g. the "category" field in your specific JSON file).

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data on App Script web app

I am attempting to create an unordered list on my app script web app by pulling an array from a range on a google sheet.
I have a function in a gs file that works properly when used within the google sheet itself:
function listTest(){
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var invSheet = sheet.getSheetByName('Inventory');
var values = invSheet.getRange(2, 3, 25).getValues();
return JSON.stringify(values);
}
I have a javascript function that I am trying to implement based on the answer given here: Create a <ul> and fill it based on a passed array
my code is pretty much exactly this, minus the options variable:
function makeUL(array) {
// Create the list element:
var list = document.createElement('ul');
for(var i = 0; i < array.length; i++) {
// Create the list item:
var item = document.createElement('li');
// Set its contents:
item.appendChild(document.createTextNode(array[i]));
// Add it to the list:
list.appendChild(item);
}
// Finally, return the constructed list:
return list;
}
I ran a simplified version of it with just one list item, and it works:
function makeList() {
var list = document.createElement('ul');
var item = document.createElement('li');
item.appendChild(document.createTextNode("This is a test."));
list.appendChild(item);
return list;
}
document.getElementById("testDiv").appendChild(makeList());
However, when I try to pull the JSON array into the function to create the unordered list using the method in the link above, I get the error message: SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data
My attempt at a function in my html to do this is:
function createList() {
var myJSON = google.script.run.listTest();
var array = JSON.parse(myJSON);
document.getElementById("testDiv").appendChild(makeUL(array));
}
createList();
I started off not using the JSON.stringify method in my listTest function. I was just ending with:
return values;
I was then getting the error 'array is undefined'.
I'm think JSON is the way to go with this, but I'm stuck.
Any help is appreciated.
Check the HTML Documentation for google.script.run. When you call google.script.run.listTest(); it doesn't actually return anything. You have to use the Success Handler which will receive returned data as a parameter. This is why your array is undefined.
EDIT: Updated This hasn't been completely tested:
function listTest(){
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var invSheet = sheet.getSheetByName('Inventory');
var values = invSheet.getRange(2, 3, 25).getValues();
return values;
}
function createList() {
google.script.run.withSuccessHandler(onSuccess)
.listTest();
}
function onSuccess(dataFromListTest){
document.getElementById("testDiv").appendChild(makeUL(dataFromListTest));
}
function makeUL(array) {
var list = document.createElement('ul');
for(var i = 0; i < array.length; i++) {
var item = document.createElement('li');
item.appendChild(document.createTextNode(array[i]));
list.appendChild(item);
}
return list;
}
See a different, basic example here: Gist - Using withSuccessHandler to Return Data
EDIT: Here is another example of an HTML File that calls a script back in the main code and puts that into a list in a div. This has been tested.
<!DOCTYPE html>
<html>
<head>
<base target="_top">
<script>
google.script.run.withSuccessHandler(onSuccess)
.getSomeData(); //getSomeData() returns [["Cell 1"],["Cell 2"],["Cell 3"],["Cell 4"],["Cell 5"]] TO onSucess() AS A PARAMETER!
function onSuccess(data) {
var div = document.getElementById('output');
var list = document.createElement('ul'); // Create a <li> node
for(var i = 0; i < data.length; i++){
var item = document.createElement('li');
item.appendChild(document.createTextNode(data[i]));
list.appendChild(item);
}
div.appendChild(list);
}
</script>
</head>
<body>
<div id="output">
</div>
</body>
</html>
See the full example here on Gist with the main code.

How to get data from API with GAS

First, I'm not a non-native, so there're some mistakes.And I'm a newbie.
function myFunction() {
var response = UrlFetchApp.fetch("https://api.ookami.me/v1/news/public?sport_id=1");
var json = JSON.parse(response.getContentText());
var news = JSON.parse(json.getContentText());
Logger.log("id");
Logger.log("url");
Logger.log("image");
}
CODE
I wrote "news" in line8's code, and that time, displayed the log. but wrote again, didn't display.
And the log displayed with id, url, image and so on, so I added the code on line6 and wrote the code on line8 to line10. But a log displayed "undefined".
I want to get data about id, url, image from this API with GAS.
And the data, I'll export to spread sheet.
You're almost there:
At this line:
var json = JSON.parse(response.getContentText());
You have all the data in this format:
I you want the element news, you need to change your line var news = JSON.parse(json.getContentText()); to var news = json.news;
Then you can loop through all the values:
for(var i = 0; i < news.length; i++) {
var obj = news[i];
Logger.log(obj.summary);
}
To export to spreadsheet, you just need to populate an Array inside the loop, and it should look like this:
var rows = []; // new values
for(var i = 0; i < news.length; i++) {
var obj = news[i];
rows.push([obj.id, obj.image,obj.url]); //your JSON entities here
}
Logger.log(rows);

Action Script 3.0 : parsing json data

I want to parse the json data shown in this link in AS3 to obtain the "message" field . I am trying with
as3corelib.swc with no success. The json data seems to be bit different . Please help me to parse this
I am using the below code
var j:Object = JSON.decode(Json_data);
var message:String = j["message"];
trace(message);
Here trace always showing null
There is no message under root object. Probably you are looking for this:
var j:Object = JSON.decode(str);
var data:Array = j["data"];
for (i = 0; i < data.length; i++) {
trace(data[i].message);
}