How to get a FetchResponse's JSON content

I’m fetching data from a Pivotal Tracker API endpoint, and it returns JSON. My problem is that I can’t figure out how to actually access that JSON data. A shortened code sample:

function storiesFrom(url) {
    let fetcher = URL.FetchRequest.fromString(url);

    let promise = fetcher.fetch();

    promise.then(response => {
        console.log(`DEBUG: status=${response.statusCode}`);  // => 200

        // The number of items that we've asked the API to return
        let expected = parseInt(response.headers["X-Tracker-Pagination-Limit"]);
        console.log(`DEBUG: expected results=${expected}`); // => 100
        
        // The number of items that the API actually returned
        let actual = parseInt(response.headers["X-Tracker-Pagination-Returned"]);
        console.log(`DEBUG: actual results=${actual}`); // => 100

        console.log(`DEBUG: body=${response.bodyString}`); // '[{stuff}, {more stuff}, ..., {item 100}]'

        let data = response.bodyData.toObject;

        console.log(`DEBUG: body=${data}`); // '[object Data]'
        console.log(`DEBUG: body is empty=${Object.keys(data).length === 0}`); // true
        console.log(`DEBUG: body as JSON=${JSON.stringify(data)}`); // '{}'
    }
}

The response.bodyString has all of the data I’d expect, except, well, it’s just a string. The docs make it sound like the response.bodyData object should hold all that data, and that its .toObject property should be a JavaScript object that I could pick apart to get at it. However, that doesn’t seem to be the case: it seems to be returning an empty object instead of the list of items I’m expecting to find.

Is there a working example of fetching data from a JSON API anywhere? I haven’t been able to find one yet.

Solved: I was looking for the undocumented JSON.parse function.

Mozilla is always a good place to go for the documentation of JavaScript:

[JSON.parse() - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse)

2 Likes

Yeah, MDN’s a great resource. My knowledge of JavaScript is weak enough that I’m still never sure what’s part of the language vs the “local” API, so I don’t often think to check it.

1 Like

Right. I think JSON.parse() is standard - but at one time it wasn’t and people used the manifestly unsafe eval() instead.

But now you know it you can apply it to eg Drafts, Scriptable, web pages etc. It’s a very useful piece of componentry in getting apps and web services to talk to each other.

That’s right – JSON.parse has been part of the JS standard since ECMAScript 5.

This post was flagged by the community and is temporarily hidden.