Reputation: 910
I'm trying to create a JSON script with retrieve, parse, and get functions as an object in PureData using the pdjs external. The pdjs external uses Google's V8 JavaScript engine. I'm able to parse built in JSON just fine, but not when it's JSON retrieved from the web. Where am I going wrong? Is my async function not correct?
Here is my code - both files should be in the same folder and pdjs should be installed in PureData.
Javascript (saved as (js-jsonparser.js'):
// Number of inlets and outlets for the Puredata object
inlets = 1;
outlets = 1;
// JSON object
const obj = {};
// To test
const json = JSON.parse('{"name":"John", "age":30, "city":"New York"}');
async function getjson(url)
{
// Wait on the fetching of the JSON
obj = await (await fetch(url).json());
// Return the JSON object
return obj;
}
function load()
{
// Retrieve the passed url
let url = arguments[0];
// Define result variable
let result;
// if an argument was passed
if (url)
{
// Call the getjson async function to retrieve the json
let g = getjson(url);
// Send 'retrieved' out the outlet
g.then(result = "retrieved");
g.then(outlet(0, result));
}
else
{
// Send 'error' out the outlet
result = "error";
outlet(0, result)
}
// to test via the pd window
//post(result);
}
function get()
{
// Send retrieved value out the outlet
outlet(0, json.name); // this works with my 'built in' JSON
outlet(0, obj.url); // this does not work with the retrieved JSON
}
Puredata patch (saved as jsonparser.pd):
#N canvas 427 166 1255 567 12;
#X declare -lib pdjs;
#X obj 264 180 l2s;
#X msg 296 136 compile;
#X text 351 134 recompile source;
#X obj 264 115 t a b;
#X obj 262 212 print;
#X msg 117 36 load https://api.nasa.gov/planetary/apod?api_key=DEMO_KEY&date=2024-06-06
;
#X msg 294 86 get url;
#X obj 504 -5 declare -lib pdjs;
#X obj 264 159 js js-jsonparser.js;
#X connect 0 0 4 0;
#X connect 1 0 8 0;
#X connect 3 0 8 0;
#X connect 3 1 1 0;
#X connect 5 0 3 0;
#X connect 6 0 3 0;
#X connect 8 0 0 0;
Upvotes: 0
Views: 51
Reputation: 3745
The way you are calling .json()
looks wrong, you should either do
obj = await (await fetch(url)).json();
or
obj = await fetch(url).then((res) => res.json())
Update: even better split this into two lines, and also make sure the request was succesful.
const response = await fetch(url)
if (!response.ok) {
console.warn("request failed: ", response.status)
return
}
const json = await response.json()
Upvotes: 1