Insert JavaScript variable into JSON - javascript

I want to insert a js variable into json (to show a message on slack).
I have tested this :
"fields":[
{
"title": "Reported by:",
"value": "'+ user + '",
"short": "false"
},
but it doesn't work and show me this :
Reported by:
'+ user +'
Thanks you !

It looks to me like you should be doing something like:
"value": "'" + user + "'",
Before user was still part of the string expression.

This is called string concatenation:
{
"title": "Reported by:",
"value": "'" + user + "'",
"short": "false"
}
The value will produce a string with the combined values, such as if user were a string value of "Jamen", the concatenated value of value would be "'Jamen'"

Related

When formatting JSON using JavaScript I get an error because of the " (double quote) flag in the data

I using the following snippet, I'm legibly displaying all JSON strings in <pre> tag with id="jsonText" on the page.
var p = document.querySelectorAll("#jsonText");
var parray = [...p]
parray.forEach(p => {
var data = p.textContent;
p.textContent = JSON.stringify(JSON.parse(data), null, 2);
});
However, I get an error when there are double quotes (") in the data.
NOTE: The problematic field in the JSON is the "hardcore" part in the value of the "description" key.
Error:
jquery.min.js:2 Uncaught SyntaxError: Expected ',' or '}' after property value in JSON at position 289
at JSON.parse (<anonymous>)
at getNews:152:33
at Array.forEach (<anonymous>)
at HTMLDocument.<anonymous> (getNews:143:20)
at e (jquery.min.js:2:30005)
at t (jquery.min.js:2:30307)
(anonymous) # getNews:152
(anonymous) # getNews:143
.
.
.
I tried various RegEx methods to correct the double quotes, but these methods caused insertions where escape characters should not be inserted, or they did not work at all.
This is the JSON text in <pre> tag. (The fields are being filled by Golang's Template.)
<pre id="jsonText">{"guid": "{{.ID}}", "title": "{{.Title}}", "url": "{{.URL}}", "description": "{{.Description}}", "sourcename": "{{.SourceName}}", "sourceurl": "{{.SourceURL}}", "imageurl": "{{.ImageURL}}", "language": "{{.Language}}", "location": "{{.Location}}", "time": {{.Time}}, "tags": "{{.Tags}}", "type": {{.Type}}}</pre>
I tried the Method 1:
var escapedData = data.replace(/\"/g, "\\\"");
console.log("Escaped JSON: ", escapedData);
jsonData = JSON.parse(escapedData);
p.textContent = JSON.stringify(jsonData, null, 2);
console.log("Fixed JSON: ", p.textContent);
NOTE: The problematic field in the JSON is the "hardcore" part in the value of the "description" key.
Input:
{
"guid": "https://www.bbc.co.uk/news/business-63648505",
"title": "Elon Musk tells Twitter staff to work long hours or leave",
"url": "https://www.bbc.co.uk/news/business-63648505?at_medium=RSS&at_campaign=KARANGA",
"description": "Elon Musk says workers at the social media firm must be "hardcore" if they want to stay, reports say.",
"sourcename": "BBC",
"sourceurl": "https://www.bbc.com/news",
"imageurl": "https://www.bbc.com/news/special/2015/newsspec_10857/bbc_news_logo.png?cb=1",
"language": "EN",
"location": "UK",
"time": 1668616715,
"tags": "",
"type": 2
}
Output:
Escaped JSON: {\"guid\": \"https://www.bbc.co.uk/news/business-63648505\", \"title\": \"Elon Musk tells Twitter staff to work long hours or leave\", \"url\": \"https://www.bbc.co.uk/news/business-63648505?at_medium=RSS&at_campaign=KARANGA\", \"description\": \"Elon Musk says workers at the social media firm must be \"hardcore\" if they want to stay, reports say.\", \"sourcename\": \"BBC\", \"sourceurl\": \"https://www.bbc.com/news\", \"imageurl\": \"https://www.bbc.com/news/special/2015/newsspec_10857/bbc_news_logo.png?cb=1\", \"language\": \"EN\", \"location\": \"UK\", \"time\": 1668616715, \"tags\": \"\", \"type\": 2}
I tried Method 2:
var escapedData = data.replace(/"([^"]+)"/g, function(match, capture) {
return '"' + capture.replace(/"/g, "\\\"") + '"';
});
jsonData = JSON.parse(escapedData);
p.textContent = JSON.stringify(jsonData, null, 2);
console.log("Fixed JSON: ", p.textContent);
The output was same as the input, at Method 2.
All I want is that the JSON text look like this.
Thanks in advance for your help.
Since you use a Goland template with Handlebars your JSON format will fail if the Description field contains quotes, as you describe. Your expanded string:
"description": "Elon Musk says workers at the social media firm must be "hardcore" if they want to stay, reports say.",
needs to be escaped to:
"description": "Elon Musk says workers at the social media firm must be \"hardcore\" if they want to stay, reports say.",
I am not familiar with Handlebars for Golang, but assuming it is compatible with regular Handlebars you can register a helper function to properly escape double quotes for use like:
"description": "{{{escapeQuotes .Description}}}",
Define the helper function to escape quotes as follows:
Handlebars.registerHelper('escapeQuotes', function (aString) {
return aString.replace(/"/g, '\\"');
});
You can try this out at the Handlebars playground at https://handlebarsjs.com/playground.html

How can I write a compound WHERE condition using documentdb?

I have a document that looks like this:
{
"email": "joan.smith#somedomain.com",
"name": {
"first": "Joan",
"last": "Smith"
}
}
How can I write a SQL query that uses a compound comparison against the entire last name?
This is effectively what I'd like to do in the WHERE:
SELECT *
FROM c
WHERE c.name.first + " " + c.name.last = "Joan Smith"
The "plural" version
SELECT *
FROM c
WHERE c.name.first + " " + c.name.last
IN ("Joan Smith", "Juan Suarez")
Both of these queries will run in the Azure Portal without error, but they return empty results. I have tried wrapping the concatenation in parentheses but this has no effect.
According to the Cosmos DB SQL APIs , if you want to implement concatenation in Cosmos DB SQL, you need to use || instead of +.
So, please modify your sql as below:
SELECT c.id,c.name
FROM c
WHERE c.name.first || " " || c.name.last = "Joan Smith"
Then you could get the results you want.
Hope it helps you.

Problems displaying .json values

I'm having trouble displaying two values on the screen( high-top and category):
This is my code:
$.getJSON('data.json', function(obj){
$.each(obj["best-seller"], function(key, value){
console.log(value.title);    
console.log(value.price); 
console.log(value.higth-top); 
console.log(value.category); 
$("#produto").append(" <b>"
+value.title+"<br/>"
+value.price+"<br/>",
+value.category+ "<br/>",
+value.higth-top+ "<br/>",
"</b>"
);
});
});
Note: Category is shown perfectly on the console, but in html it is returned NaN
And the higth-top is returned NaN in the console and also in the Html
Other values are normally displayed
I search the data in a .json, like this:
{
"best-sellers": [
{
"title": "Chuteira Nike HyperVenomX Proximo II Society",
"price": 499.9,
"installments": {
"number": 10,
"value": 49.9
},
"high-top": true,
"category": "society",
"image": "aaaa.jpg"
}
]
}
Just remove the commas inside the append.
Right now you've separated the variables by commas, giving append multiple arguments, and the plus signs acts as coercion to numbers instead of string concatenation, giving you NaN instead of the expected string
$("#produto").append(" <b>" + value.title +
"<br/>" + value.price +
"<br/>" + value.category +
"<br/>" + value['higth-top'] +
"<br/></b>"
);
Also note that hyphens aren't valid in dot-nation, as they also mean "subtract", you'd have to use bracket notation for the property higth-top
You cannot concatenate a string with commas so you have to remove them, moreover hyphens are not allowed in dot-notation
value.higth-top
here javascript understands "subtract top to value.high"
Write it as follows
$("#produto").append(" <b>" + value.title +
"<br/>" + value.price +
"<br/>" + value.category +
"<br/>" + value['high-top'] +
"<br/></b>"
);

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".

Reference object in an array in an object javascript

I hope that title makes sense... I'm very new to doing anything with Javascript, and I've been searching for a while now.
I'm using Node-RED to receive an HTTP POST containing JSON. I have the following data being posted in msg.req.body, and want to pull out objects inside of targets:
{
"policy_url": "https://alerts.newrelic.com/accounts/xxxxx/policies/7477",
"condition_id": 429539,
"condition_name": "Error rate",
"account_id": 773524,
"event_type": "INCIDENT",
"runbook_url": null,
"severity": "CRITICAL",
"incident_id": 50,
"version": "1.0",
"account_name": "Inc",
"timestamp": 1436451988232,
"details": "Error rate > 5% for at least 3 minutes",
"incident_acknowledge_url": "https://alerts.newrelic.com/accounts/xxxxxx/incidents/50/acknowledge",
"owner": "Jared Seaton",
"policy_name": "Default Policy",
"incident_url": "https://alerts.newrelic.com/accounts/xxxxxx/incidents/50",
"current_state": "acknowledged",
"targets": [{
"id": "6002060",
"name": "PHP Application",
"link": "https://rpm.newrelic.com/accounts/xxxxxx/applications/6002060?tw[start]=1436450194&tw[end]=1436451994",
"labels": {
},
"product": "APM",
"type": "Application"
}]
}
I want to format a string to send via TCP to insert an event into our event management system. So I tried the following:
msg.payload = msg.req.body.targets[0] + "|" + msg.req.body.severity + "|" + msg.req.body.current_state + "|" + msg.req.body.details + "|" + msg.req.body.condition_name + "\n\n";
return(msg);
This results in a message of:
[object Object]|CRITICAL|acknowledged|Error rate > 5% for at least 3 minutes|Error rate
I've tried a few different things, but I either get a null return, or the [object Object]. It feels like I'm close...
Can anyone assist?
Thanks in advance.
target[0] is an object and that is why you see [object Object].
You should instead do msg.req.body.targets[0].name to access the property of that object.
The result message would look something like this
PHP Application|CRITICAL|acknowledged|Error rate > 5% for at least 3 minutes|Error rate
You want JSON.stringify()
msg.payload = JSON.stringify(msg.req.body.targets[0]) + "|" + msg.req.body.severity + "|" + msg.req.body.current_state + "|" + msg.req.body.details + "|" + msg.req.body.condition_name + "\n\n";
return(msg);
This will turn the object that is stored in the first slot in the target array into it's string representation.

Categories