I’m trying to get the results from a JSONata expression to print out using HTML and Javascript, but I’m not having any luck. The expression works in the JSONata playground and produces the array I expect, but I don’t get any output when I include it in a javascript function.
Here is the expression I wrote:
items.{"Release Year":$number(($toMillis($.track.album.release_date))~>$fromMillis('[Y]')),"Track":track.name,"Artist(s)":$join($map(track.artists.name,$string),", "),"Album":track.album.name,"Genre":"","URL":$join(['https://song.link/s/',track.id]),"Release Date":track.album.release_date,"Duration":track.duration_ms,"Popularity":track.popularity,"SpotifyID":track.id,"Added to Playlist On":$toMillis($.added_at)~>$fromMillis('[M]/[D]/[Y] at [h]:[m] [P]')}
This expression is used in the following HTML. Because this is an iOS shortcut, the variable apiResponse2 is filled through a different series of commands. I know I’m getting the appropriate response from the API:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="https://cdn.jsdelivr.net/npm/jsonata/jsonata.min.js"></script>
</head>
<body>
<script>
var jsonata = require("jsonata");
function evaluateJsonata() {
var apiData = apiResponse2;
var expression = jsonata(items.{"Release Year":$number(($toMillis($.track.album.release_date))~>$fromMillis('[Y]')),"Track":track.name,"Artist(s)":$join($map(track.artists.name,$string),", "),"Album":track.album.name,"Genre":"","URL":$join(['https://song.link/s/',track.id]),"Release Date":track.album.release_date,"Duration":track.duration_ms,"Popularity":track.popularity,"SpotifyID":track.id,"Added to Playlist On":$toMillis($.added_at)~>$fromMillis('[M]/[D]/[Y] at [h]:[m] [P]')});
var result = expression.evaluate(apiData);
document.write(JSON.stringify(result))
}
</script>
</body>
</html>
You can see a sample of the JSON returned by the Spotify API at this link. The API JSON is also in the JSONata playground.
Because this is an iOS shortcut, I post the above in a text block, then do the following:
Screenshot of Used Shortcut Actions
But, I don’t get the expected array back. In fact, I get nothing back. I’m hoping my error is with the Javascript.
Any help debugging this would be greatly appreciated.