Skip to content
TORNLIFE More

JAVASCRIPT API REQUEST

Started by Trenix [2264772] on in API Development.

2 replies · 170 views · thread synced · 4 days ago · View on torn.com
About this thread

Posts archived: 3 / 3 posts (100%) · the total is Torn's reply count + the opening post at the last fetch

Counted by TornLife from the archived posts.

Archived posts
3
Discussion span
→
People posting
2
Likes on archived posts
2
Authority score
51 / 100
Historical score
17 / 100
Story score
26 / 100
Engagement score
45 / 100
Trenix [2264772]
Can some one help me out here. How do i make a javascript api request and filter the response for a specific value like my networth, or my faction name. How to i filter the arrays i get as responses???

Help !!!
SVD_NL [2363978]
You can go to api.torn.com to test all requests you make, and you can see how the url changes depending on what you want to know. Set it to "pretty" to get a better understanding of how it's nested. The further to the side it is, the further it's nested.

It's hard to give a catch-all code to process each request, as they're very different.

Important distinction: the return from the API request is a JSON object, not an array.

I've sent you a snippet of code before on how I set up making the request. I used the .split() method. I got the idea from this video guide: (he will probably explain it a lot better) https://youtu.be/k0su6345KDIhttps://youtu.be/k0su6345KDI

You first need to parse the content. I used:

var content = response.getContentText();
var json = JSON.parse(content);

As an example: when you do a user "profile" request, the return will have some elements that say "string":value. These can be returned easily, to get the level for example:

return json.level
//Returns the value of the string "level", in my case it would return 20

If you want to be something nested one level further, for example the last action, you can use the .split() method

First, you need to assign which of the nested objects you want to access to a variable:

var xpath = "last_action"

Then you turn the nested object into an iterable object and loop over it:

var patharray = xpath.split("/") //I don't really use the "/" but I think it breaks the code for some reason when I remove it so I leave it in
for(i=0;i<patharray.length;i++){
json = json[patharray[i*]] //without the asterisk, forum won't show if I don't put that there
}

Now, if the data you want is at this level, you can be it.
return json.timestamp //returns the timestamp
return json.relative //returns the string "active x time ago"

For networth: do the user "networth" API call, set the var xpath as "networth", return json.total (or whichever one you want). Always test the API requests, as some requests (like networth) can only be done by someone with permissions to the request (in this case only the user that the API key belongs to).

Feel free to ask any more questions