Variable JSON values / methods inside JSON - javascript

My website has a functionality of synthesizing speech from preset text. I wanted to diversify it to include multiple languages. Hence, I chose to move the texts to JSON voiceOutputs.
{
"english": {
"actionStarted": "Action has started",
"success": "Success",
"error": "Error occured",
"goodNight": "Good Night"
},
"japanese": {
"actionStarted": "アクションが始まりました",
"success": "成功しました",
"error": "エラーが発生しました",
"goodNight": "おやすみなさい"
}
}
And I can use these texts by
voiceOutputs.[getCookie("voiceLang")].actionStarted;
How do I revamp my variable dependent texts into JSON structure as the sentence pattern differs with languages.
Eg.
"Good bye " + variableforName
variableForName + "おやすみなさい。"
I can't call "goodBye" and "おやすみなさい" directly as I want to create a generalized version of output and I need a proper word pattern depending on language.
Work-arounds:
1. Using a function (easy but not optimized and takes a lot of work)
function goodNight(variableForName) {
if (getCookie("voiceLang") == "japanese") {
return variableForName+voiceOutputs.[getCookie("voiceLang")].goodNight;
}
else if (getCookie("voiceLang") == "english") {
return voiceOutputs.[getCookie("voiceLang")].goodNight + " " + variableForName;
}
Methods inside voiceOutputs JSON:
Is it possible???

You can use a library for string formats (I do not know of any solid ones, please edit my answer or post your own), but you could also just use Vanilla Javascript's String.prototype.replace Combined with a character pattern you expect not to be seen in the same string otherwise
E.g.
"Good bye {{%name}}";
"{{%name}}おやすみなさい。";
You can then use both the same way, by calling .replace('{{%name}}', nameVariable)

Related

TinyMce 4 util.i18n.translate() usage

I try since hours and using the (very less helpful API documentation :S) to get translation for my plugin working.
tinymce.translate('Cut'); // returns Ausschneiden for de
So far, so good.
tinymce.translate('myplugin.test'); // returns myplugin.test
I checked tinymce.i18n.data and can see through inspector that it contains the data I added with
tinymce.addI18n('de.myplugin', {
"test": 'test label'
});
before.
This is probably something stupid but I can not figure it out.
UPDATE
I now add my own functionality to do it manually as I can not figure it out how to do it:
plugin_translate = function(val) {
return (eval('tinymce.i18n.data.' + tinymce.settings.language + '.' + val) != undefined)
? eval('tinymce.i18n.data.' + tinymce.settings.language + '.' + val)
: val;
}
And my plugin/langs/de.js looks like this
tinymce.addI18n('de', { 'plugin': { "title" : 'Titel' }});
This doesn't look right but at the moment it works until someone enlighten me.
Translations are registered using tinymce.addI18n(langCode, translationMap) or tinymce.util.I18n.add(langCode, translationMap).
The first parameter is a language code like "en", "en_US" or "de". This should be the same value used for the language init property. Note that you should not include the plugin prefix here.
The second parameter is a map of translation-key to translation pairs. The translations can take positional arguments like {0} and {1}. You should prefix your keys with your plugin name to avoid naming clashes. For example:
{
"myplugin.test": "test label",
"myplugin.greeting": "Hello {0}, you are welcome"
}
So combining all those parts together you might register English and German translations like:
tinymce.addI18n("en", {
"myplugin.title": "My Plugin",
"myplugin.greeting": "Hello {0}, you are welcome"
});
tinymce.addI18n("de", {
"myplugin.title": "Mein Plugin",
"myplugin.greeting": "Hallo {0}, du bist willkommen"
});
Then to use the translation call tinymce.translate(translationKey) which returns the translated string. For a string without arguments you can just pass the same key you used in the map. For example:
var title = tinymce.translate("myplugin.title");
If your translation has parameters you have to wrap the key up in an array. For example:
var name = getName(); // get the name from the user
var greeting = tinymce.translate(["myplugin.greeting", name]);
If for some reason you need to override the translation you can provide an object with a raw string. For example:
var name = getName(); // get the name from the user
var key = name === "James" ? {"raw": "Go away!"} : ["myplugin.greeting", name];
var greeting = tinymce.translate(key);

How to parse string contained json object with escape characters?

I can't parse this following string with JSON.parse() function.
At first I tried to remove the initial and final double quotes. And then I removed the escape characters.
How to parse this type of JSON response?
{
"timestamp": 1490545425158,
"reports": {
"statusCode": 200,
"body": "{\"responseCode\":\"200\",\"responseMessage\":\"Success\",\"getevent\":[{\"eventID\":\"24844563\",\"channelId\":21,\"channelStbNumber\":\"861\",\"channelHD\":\"false\",\"channelTitle\":\"Gold\",\"epgEventImage\":null,\"certification\":\"U\",\"displayDateTimeUtc\":\"2017-03-25 16:00:00.0\",\"displayDateTime\":\"2017-03-26 00:00:00.0\",\"displayDuration\":\"06:00:00\",\"siTrafficKey\":\"1:2169:30291203\",\"programmeTitle\":\"Great Golden Oldies\",\"programmeId\":\"GBSSJ\",\"episodeId\":\"\",\"shortSynopsis\":\"Mixture of '50s to '70s songs.\",\"longSynopsis\":null,\"actors\":\"\",\"directors\":\"\",\"producers\":\"\",\"genre\":\"Music & Dance\",\"subGenre\":\"General\",\"live\":false,\"premier\":false,\"ottBlackout\":false,\"highlight\":null,\"contentId\":null,\"contentImage\":null,\"groupKey\":null,\"vernacularData\":[]},{\"eventID\":\"24844564\",\"channelId\":21,\"channelStbNumber\":\"861\",\"channelHD\":\"false\",\"channelTitle\":\"Gold\",\"epgEventImage\":null,\"certification\":\"U\",\"displayDateTimeUtc\":\"2017-03-25 22:00:00.0\",\"displayDateTime\":\"2017-03-26 06:00:00.0\",\"displayDuration\":\"04:00:00\",\"siTrafficKey\":\"1:2169:30291204\",\"programmeTitle\":\"Breakfast Time\",\"programmeId\":\"GBSSK\",\"episodeId\":\"\",\"shortSynopsis\":\"Wake up to Golden Oldies.\",\"longSynopsis\":null,\"actors\":\"\",\"directors\":\"\",\"producers\":\"\",\"genre\":\"Music & Dance\",\"subGenre\":\"General\",\"live\":false,\"premier\":false,\"ottBlackout\":false,\"highlight\":null,\"contentId\":null,\"contentImage\":null,\"groupKey\":null,\"vernacularData\":[]},{\"eventID\":\"24844565\",\"channelId\":21,\"channelStbNumber\":\"861\",\"channelHD\":\"false\",\"channelTitle\":\"Gold\",\"epgEventImage\":null,\"certification\":\"U\",\"displayDateTimeUtc\":\"2017-03-26 02:00:00.0\",\"displayDateTime\":\"2017-03-26 10:00:00.0\",\"displayDuration\":\"02:00:00\",\"siTrafficKey\":\"1:2169:30291205\",\"programmeTitle\":\"The Best Mix\",\"programmeId\":\"GBSSE\",\"episodeId\":\"\",\"shortSynopsis\":\"Best songs for the day.\",\"longSynopsis\":null,\"actors\":\"\",\"directors\":\"\",\"producers\":\"\",\"genre\":\"Music & Dance\",\"subGenre\":\"General\",\"live\":false,\"premier\":false,\"ottBlackout\":false,\"highlight\":null,\"contentId\":null,\"contentImage\":null,\"groupKey\":null,\"vernacularData\":[]},{\"eventID\":\"24844566\",\"channelId\":21,\"channelStbNumber\":\"861\",\"channelHD\":\"false\",\"channelTitle\":\"Gold\",\"epgEventImage\":null,\"certification\":\"U\",\"displayDateTimeUtc\":\"2017-03-26 04:00:00.0\",\"displayDateTime\":\"2017-03-26 12:00:00.0\",\"displayDuration\":\"03:00:00\",\"siTrafficKey\":\"1:2169:30291206\",\"programmeTitle\":\"Lunch Time with Oldies\",\"programmeId\":\"GBSSH\",\"episodeId\":\"\",\"shortSynopsis\":\"Mixture of '50s to '70s songs.\",\"longSynopsis\":null,\"actors\":\"\",\"directors\":\"\",\"producers\":\"\",\"genre\":\"Music & Dance\",\"subGenre\":\"General\",\"live\":false,\"premier\":false,\"ottBlackout\":false,\"highlight\":null,\"contentId\":null,\"contentImage\":null,\"groupKey\":null,\"vernacularData\":[]},{\"eventID\":\"24844567\",\"channelId\":21,\"channelStbNumber\":\"861\",\"channelHD\":\"false\",\"channelTitle\":\"Gold\",\"epgEventImage\":null,\"certification\":\"U\",\"displayDateTimeUtc\":\"2017-03-26 07:00:00.0\",\"displayDateTime\":\"2017-03-26 15:00:00.0\",\"displayDuration\":\"03:00:00\",\"siTrafficKey\":\"1:2169:30291207\",\"programmeTitle\":\"Your Favourites\",\"programmeId\":\"GBSSD\",\"episodeId\":\"\",\"shortSynopsis\":\"Giving you the songs you grew up with.\",\"longSynopsis\":null,\"actors\":\"\",\"directors\":\"\",\"producers\":\"\",\"genre\":\"Music & Dance\",\"subGenre\":\"General\",\"live\":false,\"premier\":false,\"ottBlackout\":false,\"highlight\":null,\"contentId\":null,\"contentImage\":null,\"groupKey\":null,\"vernacularData\":[]},{\"eventID\":\"24844568\",\"channelId\":21,\"channelStbNumber\":\"861\",\"channelHD\":\"false\",\"channelTitle\":\"Gold\",\"epgEventImage\":null,\"certification\":\"U\",\"displayDateTimeUtc\":\"2017-03-26 10:00:00.0\",\"displayDateTime\":\"2017-03-26 18:00:00.0\",\"displayDuration\":\"06:00:00\",\"siTrafficKey\":\"1:2169:30291208\",\"programmeTitle\":\"Starry Night\",\"programmeId\":\"GBSSF\",\"episodeId\":\"\",\"shortSynopsis\":\"More of the golden songs.\",\"longSynopsis\":null,\"actors\":\"\",\"directors\":\"\",\"producers\":\"\",\"genre\":\"Music & Dance\",\"subGenre\":\"General\",\"live\":false,\"premier\":false,\"ottBlackout\":false,\"highlight\":null,\"contentId\":null,\"contentImage\":null,\"groupKey\":null,\"vernacularData\":[]}]}"
}
}
Assuming it's really a string (e.g., from a network request or similar), you use JSON.parse on it. Then, since the body property is a string containing JSON (e.g., its contents have been double-stringified for some reason), you parse that again.
Example:
var json = '{\n' +
' "timestamp": 1490545425158,\n' +
' "reports": {\n' +
' "statusCode": 200,\n' +
' "body": "{\\"responseCode\\":\\"200\\",\\"responseMessage\\":\\"Success\\",\\"getevent\\":[{\\"eventID\\":\\"24844563\\",\\"channelId\\":21,\\"channelStbNumber\\":\\"861\\",\\"channelHD\\":\\"false\\",\\"channelTitle\\":\\"Gold\\",\\"epgEventImage\\":null,\\"certification\\":\\"U\\",\\"displayDateTimeUtc\\":\\"2017-03-25 16:00:00.0\\",\\"displayDateTime\\":\\"2017-03-26 00:00:00.0\\",\\"displayDuration\\":\\"06:00:00\\",\\"siTrafficKey\\":\\"1:2169:30291203\\",\\"programmeTitle\\":\\"Great Golden Oldies\\",\\"programmeId\\":\\"GBSSJ\\",\\"episodeId\\":\\"\\",\\"shortSynopsis\\":\\"Mixture of \'50s to \'70s songs.\\",\\"longSynopsis\\":null,\\"actors\\":\\"\\",\\"directors\\":\\"\\",\\"producers\\":\\"\\",\\"genre\\":\\"Music & Dance\\",\\"subGenre\\":\\"General\\",\\"live\\":false,\\"premier\\":false,\\"ottBlackout\\":false,\\"highlight\\":null,\\"contentId\\":null,\\"contentImage\\":null,\\"groupKey\\":null,\\"vernacularData\\":[]},{\\"eventID\\":\\"24844564\\",\\"channelId\\":21,\\"channelStbNumber\\":\\"861\\",\\"channelHD\\":\\"false\\",\\"channelTitle\\":\\"Gold\\",\\"epgEventImage\\":null,\\"certification\\":\\"U\\",\\"displayDateTimeUtc\\":\\"2017-03-25 22:00:00.0\\",\\"displayDateTime\\":\\"2017-03-26 06:00:00.0\\",\\"displayDuration\\":\\"04:00:00\\",\\"siTrafficKey\\":\\"1:2169:30291204\\",\\"programmeTitle\\":\\"Breakfast Time\\",\\"programmeId\\":\\"GBSSK\\",\\"episodeId\\":\\"\\",\\"shortSynopsis\\":\\"Wake up to Golden Oldies.\\",\\"longSynopsis\\":null,\\"actors\\":\\"\\",\\"directors\\":\\"\\",\\"producers\\":\\"\\",\\"genre\\":\\"Music & Dance\\",\\"subGenre\\":\\"General\\",\\"live\\":false,\\"premier\\":false,\\"ottBlackout\\":false,\\"highlight\\":null,\\"contentId\\":null,\\"contentImage\\":null,\\"groupKey\\":null,\\"vernacularData\\":[]},{\\"eventID\\":\\"24844565\\",\\"channelId\\":21,\\"channelStbNumber\\":\\"861\\",\\"channelHD\\":\\"false\\",\\"channelTitle\\":\\"Gold\\",\\"epgEventImage\\":null,\\"certification\\":\\"U\\",\\"displayDateTimeUtc\\":\\"2017-03-26 02:00:00.0\\",\\"displayDateTime\\":\\"2017-03-26 10:00:00.0\\",\\"displayDuration\\":\\"02:00:00\\",\\"siTrafficKey\\":\\"1:2169:30291205\\",\\"programmeTitle\\":\\"The Best Mix\\",\\"programmeId\\":\\"GBSSE\\",\\"episodeId\\":\\"\\",\\"shortSynopsis\\":\\"Best songs for the day.\\",\\"longSynopsis\\":null,\\"actors\\":\\"\\",\\"directors\\":\\"\\",\\"producers\\":\\"\\",\\"genre\\":\\"Music & Dance\\",\\"subGenre\\":\\"General\\",\\"live\\":false,\\"premier\\":false,\\"ottBlackout\\":false,\\"highlight\\":null,\\"contentId\\":null,\\"contentImage\\":null,\\"groupKey\\":null,\\"vernacularData\\":[]},{\\"eventID\\":\\"24844566\\",\\"channelId\\":21,\\"channelStbNumber\\":\\"861\\",\\"channelHD\\":\\"false\\",\\"channelTitle\\":\\"Gold\\",\\"epgEventImage\\":null,\\"certification\\":\\"U\\",\\"displayDateTimeUtc\\":\\"2017-03-26 04:00:00.0\\",\\"displayDateTime\\":\\"2017-03-26 12:00:00.0\\",\\"displayDuration\\":\\"03:00:00\\",\\"siTrafficKey\\":\\"1:2169:30291206\\",\\"programmeTitle\\":\\"Lunch Time with Oldies\\",\\"programmeId\\":\\"GBSSH\\",\\"episodeId\\":\\"\\",\\"shortSynopsis\\":\\"Mixture of \'50s to \'70s songs.\\",\\"longSynopsis\\":null,\\"actors\\":\\"\\",\\"directors\\":\\"\\",\\"producers\\":\\"\\",\\"genre\\":\\"Music & Dance\\",\\"subGenre\\":\\"General\\",\\"live\\":false,\\"premier\\":false,\\"ottBlackout\\":false,\\"highlight\\":null,\\"contentId\\":null,\\"contentImage\\":null,\\"groupKey\\":null,\\"vernacularData\\":[]},{\\"eventID\\":\\"24844567\\",\\"channelId\\":21,\\"channelStbNumber\\":\\"861\\",\\"channelHD\\":\\"false\\",\\"channelTitle\\":\\"Gold\\",\\"epgEventImage\\":null,\\"certification\\":\\"U\\",\\"displayDateTimeUtc\\":\\"2017-03-26 07:00:00.0\\",\\"displayDateTime\\":\\"2017-03-26 15:00:00.0\\",\\"displayDuration\\":\\"03:00:00\\",\\"siTrafficKey\\":\\"1:2169:30291207\\",\\"programmeTitle\\":\\"Your Favourites\\",\\"programmeId\\":\\"GBSSD\\",\\"episodeId\\":\\"\\",\\"shortSynopsis\\":\\"Giving you the songs you grew up with.\\",\\"longSynopsis\\":null,\\"actors\\":\\"\\",\\"directors\\":\\"\\",\\"producers\\":\\"\\",\\"genre\\":\\"Music & Dance\\",\\"subGenre\\":\\"General\\",\\"live\\":false,\\"premier\\":false,\\"ottBlackout\\":false,\\"highlight\\":null,\\"contentId\\":null,\\"contentImage\\":null,\\"groupKey\\":null,\\"vernacularData\\":[]},{\\"eventID\\":\\"24844568\\",\\"channelId\\":21,\\"channelStbNumber\\":\\"861\\",\\"channelHD\\":\\"false\\",\\"channelTitle\\":\\"Gold\\",\\"epgEventImage\\":null,\\"certification\\":\\"U\\",\\"displayDateTimeUtc\\":\\"2017-03-26 10:00:00.0\\",\\"displayDateTime\\":\\"2017-03-26 18:00:00.0\\",\\"displayDuration\\":\\"06:00:00\\",\\"siTrafficKey\\":\\"1:2169:30291208\\",\\"programmeTitle\\":\\"Starry Night\\",\\"programmeId\\":\\"GBSSF\\",\\"episodeId\\":\\"\\",\\"shortSynopsis\\":\\"More of the golden songs.\\",\\"longSynopsis\\":null,\\"actors\\":\\"\\",\\"directors\\":\\"\\",\\"producers\\":\\"\\",\\"genre\\":\\"Music & Dance\\",\\"subGenre\\":\\"General\\",\\"live\\":false,\\"premier\\":false,\\"ottBlackout\\":false,\\"highlight\\":null,\\"contentId\\":null,\\"contentImage\\":null,\\"groupKey\\":null,\\"vernacularData\\":[]}]}"\n' +
' }\n' +
'}';
var parsed = JSON.parse(json);
parsed.reports.body = JSON.parse(parsed.reports.body); // This is the second parse
console.log(parsed);
But: Ideally, you'd want to fix the source which is unnecessarily double-stringifying body.
Of course, if something's already done the first parse for you (for instance, many libraries will automatically parse JSON retrieved via ajax), then of course you don't need that first parse:
var parsed = {
"timestamp": 1490545425158,
"reports": {
"statusCode": 200,
"body": "{\"responseCode\":\"200\",\"responseMessage\":\"Success\",\"getevent\":[{\"eventID\":\"24844563\",\"channelId\":21,\"channelStbNumber\":\"861\",\"channelHD\":\"false\",\"channelTitle\":\"Gold\",\"epgEventImage\":null,\"certification\":\"U\",\"displayDateTimeUtc\":\"2017-03-25 16:00:00.0\",\"displayDateTime\":\"2017-03-26 00:00:00.0\",\"displayDuration\":\"06:00:00\",\"siTrafficKey\":\"1:2169:30291203\",\"programmeTitle\":\"Great Golden Oldies\",\"programmeId\":\"GBSSJ\",\"episodeId\":\"\",\"shortSynopsis\":\"Mixture of '50s to '70s songs.\",\"longSynopsis\":null,\"actors\":\"\",\"directors\":\"\",\"producers\":\"\",\"genre\":\"Music & Dance\",\"subGenre\":\"General\",\"live\":false,\"premier\":false,\"ottBlackout\":false,\"highlight\":null,\"contentId\":null,\"contentImage\":null,\"groupKey\":null,\"vernacularData\":[]},{\"eventID\":\"24844564\",\"channelId\":21,\"channelStbNumber\":\"861\",\"channelHD\":\"false\",\"channelTitle\":\"Gold\",\"epgEventImage\":null,\"certification\":\"U\",\"displayDateTimeUtc\":\"2017-03-25 22:00:00.0\",\"displayDateTime\":\"2017-03-26 06:00:00.0\",\"displayDuration\":\"04:00:00\",\"siTrafficKey\":\"1:2169:30291204\",\"programmeTitle\":\"Breakfast Time\",\"programmeId\":\"GBSSK\",\"episodeId\":\"\",\"shortSynopsis\":\"Wake up to Golden Oldies.\",\"longSynopsis\":null,\"actors\":\"\",\"directors\":\"\",\"producers\":\"\",\"genre\":\"Music & Dance\",\"subGenre\":\"General\",\"live\":false,\"premier\":false,\"ottBlackout\":false,\"highlight\":null,\"contentId\":null,\"contentImage\":null,\"groupKey\":null,\"vernacularData\":[]},{\"eventID\":\"24844565\",\"channelId\":21,\"channelStbNumber\":\"861\",\"channelHD\":\"false\",\"channelTitle\":\"Gold\",\"epgEventImage\":null,\"certification\":\"U\",\"displayDateTimeUtc\":\"2017-03-26 02:00:00.0\",\"displayDateTime\":\"2017-03-26 10:00:00.0\",\"displayDuration\":\"02:00:00\",\"siTrafficKey\":\"1:2169:30291205\",\"programmeTitle\":\"The Best Mix\",\"programmeId\":\"GBSSE\",\"episodeId\":\"\",\"shortSynopsis\":\"Best songs for the day.\",\"longSynopsis\":null,\"actors\":\"\",\"directors\":\"\",\"producers\":\"\",\"genre\":\"Music & Dance\",\"subGenre\":\"General\",\"live\":false,\"premier\":false,\"ottBlackout\":false,\"highlight\":null,\"contentId\":null,\"contentImage\":null,\"groupKey\":null,\"vernacularData\":[]},{\"eventID\":\"24844566\",\"channelId\":21,\"channelStbNumber\":\"861\",\"channelHD\":\"false\",\"channelTitle\":\"Gold\",\"epgEventImage\":null,\"certification\":\"U\",\"displayDateTimeUtc\":\"2017-03-26 04:00:00.0\",\"displayDateTime\":\"2017-03-26 12:00:00.0\",\"displayDuration\":\"03:00:00\",\"siTrafficKey\":\"1:2169:30291206\",\"programmeTitle\":\"Lunch Time with Oldies\",\"programmeId\":\"GBSSH\",\"episodeId\":\"\",\"shortSynopsis\":\"Mixture of '50s to '70s songs.\",\"longSynopsis\":null,\"actors\":\"\",\"directors\":\"\",\"producers\":\"\",\"genre\":\"Music & Dance\",\"subGenre\":\"General\",\"live\":false,\"premier\":false,\"ottBlackout\":false,\"highlight\":null,\"contentId\":null,\"contentImage\":null,\"groupKey\":null,\"vernacularData\":[]},{\"eventID\":\"24844567\",\"channelId\":21,\"channelStbNumber\":\"861\",\"channelHD\":\"false\",\"channelTitle\":\"Gold\",\"epgEventImage\":null,\"certification\":\"U\",\"displayDateTimeUtc\":\"2017-03-26 07:00:00.0\",\"displayDateTime\":\"2017-03-26 15:00:00.0\",\"displayDuration\":\"03:00:00\",\"siTrafficKey\":\"1:2169:30291207\",\"programmeTitle\":\"Your Favourites\",\"programmeId\":\"GBSSD\",\"episodeId\":\"\",\"shortSynopsis\":\"Giving you the songs you grew up with.\",\"longSynopsis\":null,\"actors\":\"\",\"directors\":\"\",\"producers\":\"\",\"genre\":\"Music & Dance\",\"subGenre\":\"General\",\"live\":false,\"premier\":false,\"ottBlackout\":false,\"highlight\":null,\"contentId\":null,\"contentImage\":null,\"groupKey\":null,\"vernacularData\":[]},{\"eventID\":\"24844568\",\"channelId\":21,\"channelStbNumber\":\"861\",\"channelHD\":\"false\",\"channelTitle\":\"Gold\",\"epgEventImage\":null,\"certification\":\"U\",\"displayDateTimeUtc\":\"2017-03-26 10:00:00.0\",\"displayDateTime\":\"2017-03-26 18:00:00.0\",\"displayDuration\":\"06:00:00\",\"siTrafficKey\":\"1:2169:30291208\",\"programmeTitle\":\"Starry Night\",\"programmeId\":\"GBSSF\",\"episodeId\":\"\",\"shortSynopsis\":\"More of the golden songs.\",\"longSynopsis\":null,\"actors\":\"\",\"directors\":\"\",\"producers\":\"\",\"genre\":\"Music & Dance\",\"subGenre\":\"General\",\"live\":false,\"premier\":false,\"ottBlackout\":false,\"highlight\":null,\"contentId\":null,\"contentImage\":null,\"groupKey\":null,\"vernacularData\":[]}]}"
}
};
parsed.reports.body = JSON.parse(parsed.reports.body); // Parse body
console.log(parsed);
You need to parse the body:
JSON.parse(object.reports.body)
The rest is already "parsed".

Are if and else if statements bugged in Google Apps Script?

I'm fairly new to GAS and Javascript in general and have searched far and wide to find an answer to why this isn't working, but haven't found a solution. I was wondering if one of you guys could find the problem. Here's my code:
function maintenanceRequest() {
var findFirstRequest = GmailApp.search("to:censored label:ems-request AND is:unread", 0, 1)[0];
var firstRequest = findFirstRequest.getMessages()[0];
var parseRequest = firstRequest.getPlainBody();
var requestString = String(parseRequest);
if ("Mark archived mail as read" == requestString) {
markArchivedAsRead();
findFirstRequest.moveToArchive();
}
else if ("Cleanup" == requestString) {
weeklyCleanup();
findFirstRequest.moveToArchive();
}
else {
GmailApp.sendEmail("censored", "Failure to parse command", "The EMS has recieved your request but has failed to recognize the command '" + parseRequest + "'. Please try again, using the terms 'Mark archived as read' or 'Cleanup'. If you would like to add an eligible command, please refer to function 'maintenanceRequest'.", {
name: "Email Maintenance Service",
from: "censored"
})
//Add moveToArchive line here after debugging
}
}
The code always skips the if and else if statements and jumps to the else statement, regardless of the email's content. I've tried using both == and === to no avail, and have tried switching the sides that the arguments are on. To no avail. I even created a new var, requestString to convert parseRequest to a string, even though I'm like 99% certain that it already is a string.. so what gives? Where's the problem?
Try adding trim to the string: requestString = requestString.trim()
It's usually a safe bet to use trim on any string you're getting from another service.

Can I 'match' values in 2 arrays and then use the subsequent 'matched' value?

I'm trying to achieve the following though with my intermediate JavaScript skills I'm not sure if this is possible.
This is related in part to this question.
Now I have 2 arrays
a) Has the various language in (e.g. "en-GB", "fr", "de" etc)
b) Has a suffix of a URL based on the browser language above (e.g. "fr/","de/","uk/")
What I am trying to achieve is:
1) User hits a page, browser detects which browser it is using from the array (a)
2) Depending on what the browser is based on (a), it then searches through (b) and if they match, e.g. if the language is "fr" it will use the suffix "fr/" from the array in (b).
3) It will then add this suffix to a top level domain (which is always constant)
Is this even possible to achieve (I'm sure it is)? Can it be done purely via JavaScript (or JQuery)? How would I go about doing this?
Here's some of the code I have so far:
var IAB_Array = new Array("de-at","nl-be","fr-be","da","de","hu","en-ie","ga","es","fr","it","nl","no","pl","en","en-GB","en-US","en-gb","en-us"); //language array
var IAB_suffix = new Array("at/","be-nl/","be-fr","den/","de/","hu/","ie/","es/","fr/","it/","nl/","nor/","pl/","uk/"); //URL suffix Array
var IAB_lang = "en-GB"; //default language
var IAB_link = "http://www.mysitegoeshere/";
if(navigator.browserLanguage) IAB_lang = navigator.browserLanguage; //change lang if detection supported
if(window.navigator.language) IAB_lang = window.navigator.language; //change lang if detection supported
function IAB_Lang_detect () { //execute search
for (var i=0;i<IAB_Array.length;i++) {
if(IAB_Array[i]==IAB_lang) {
document.write(IAB_Array[i]); //output matched array value
}
}
return false;
}
var IAB_URL = ""+IAB_link+IAB_suffix[1]+""; //this is the resulting URL
document.write(IAB_URL);
IAB_Lang_detect ();
I hope someone can help as I'm a little confused! It's more so the matching the values from the 2 arrays and then subsequently selecting the correct suffix that I'm having trouble with.
Thanks
(function () {
"use strict";
var lang_map = {
"de-at": "at/",
"nl-be": "be-nl/",
"fr-be": "be-fr",
"da": "den/",
"de": "de/",
"hu": "hu/",
"en-ie": "ie/",
"ga": "ie/",
"es": "es/",
"fr": "fr/",
"it": "it/",
"nl": "nl/",
"no": "nor/",
"pl": "pl/",
"en": "uk/",
"en-GB": "uk/",
"en-US": "uk/",
"en-gb": "uk/",
"en-us": "uk/"
},
lang = (navigator && navigator.browserLanguage) || (window.navigator && window.navigator.language) || "en-GB";
window.location = "http://www.mysitegoeshere/" + lang_map[lang];
}());
I'd do it differently and use an object:
var IAB_Object = { "it-It": "it/", "en-Gb": "en/" ....}
if(IAB_Object.hasOwnProperty(IAB_lang)){
//you have a match, the suffix is
var suffix = IAB_Object[IAB_lang];
}else{
//you don't have a match use a standard language
}
I probably wouldn't use arrays for this at all. You can use an object:
var IABInfo = {
"de-at": "at/",
"ln-be": "be-nl/",
// ...and so on
};
Then index directly into that object:
var value = IABInfo[IABLang]; // Where IABLang contains a string, like "de-at"
So:
var suffix = IABInfo[IABLang];
if (suffix) { // Did we have it?
document.write(suffix);
}
This works because all JavaScript objects are free-form key/value maps. Here's a simpler example:
var lifeTheUniverseAndEverything = {
answer: 42,
question: "?"
};
You can look up a property either using dotted notation with a literal, or by using square bracket ([]) notation with a string. So all four of these output exactly the same thing:
// 1. Dotted notation with a literal:
console.log("The answer is " + lifeTheUniverseAndEverything.answer);
// 2. Bracketed notation with a string
console.log("The answer is " + lifeTheUniverseAndEverything["answer"]);
// 3. The string needn't be a literal, it can come from a variable...
var name = "answer";
console.log("The answer is " + lifeTheUniverseAndEverything[name]);
// 4. ...or indeed any expression:
console.log("The answer is " + lifeTheUniverseAndEverything["a" + "n" + "swer"]);
So by making your IAB info a map in an object literal, you can make it much easier to look things up: Just use bracketed notation with the desired language code.

Javascript RegEx Help

I want to take strings like:
Submit Changes
Create New
Update Record
Save Item
and convert them to:
Submitting Changes
Creating New
Updating Record
Saving Item
with a function like:
var ConvertToProgressivePresent = (function(){
// cache this regex
var rProgressivePresent = /\b(?:(Submi(t))|(Creat|Sav|Updat)e)\b/i;
return function(phrase){
return phrase.replace(rProgressivePresent, "$1$2$3ing");
};
}());
This above regex works but doesn't seem like the best way to do it. I don't like the grouping here where 1-2 groups are always empty when there is a match.
Got any suggestions or improvements?
If you have specific words to replace with then you could make a word bank. Have the words and their replacement stored in an object and then loop through it.
var ConvertToProgressivePresent = (function() {
var replaceValues = {
"Submit": "Submitting",
"Create": "Creating",
"Update": "Updating",
"Save": "Saving"
}
return function(phrase) {
for (var item in replaceValues) {
phrase = phrase.replace(item, replaceValues[item]);
}
return phrase;
};
}());
Here is a JSFiddle Example
I think you should probablly use CASE statments instead. Regex isn't the most efficient way of doing things...and that is probably best that it doesn't cuz you know the old saying.
Wow, I have this problem...I know, I'll use regex...ok, now you have two problems 90)
First off, it doesn't appear to me that your regex does quite what you want anyway in that I don't see a second "t" added when changing submit to submitting.
However, I don't think I would use regex for this task at all anyway. If you are just trying to replace one word with another, and the word always comes at the beginning of the string, I might do something like:
function ReplaceIfBeginsWith(wholeString, checkFor, replaceWith)
{
if (wholeString.indexOf(checkFor + ' ') == 0)
{
return replaceWith + ' ' + wholeString.substr(checkFor.length + 1);
}
if (wholeString == checkFor)
{
return replaceWith;
}
return wholeString;
}
Then, you can call the function with each of the words you would want to replace. If you want case-insensitivity, just check against lowercase versions of all the strings.

Categories