Im making a discord bot, and I have a URL here which has some raw json: link here and I want one of the values (hashrateString) to be put inside a embed like:
hashrateString: 1GH
is there a way to do that and if so how?
I never tried this with an external link but it should work the same way.
FIRST: write somewhere high up in your code this line
var fs = require('fs');
var data = JSON.parse(fs.readFileSync('http://ric.pikapools.com/api/stats', 'utf8'));
After you can basically do whatever you want with your new object. There was no hashrateString: 1GH, but hashrateString: 4.68 GH should be accessible with data.algos.primesr.hashrateString (Output: 4.68 GH)
If it, for some weird reason, doesn't accept an URL, just try to copy&paste the text in a json file if possible, and use the path to it
I was able to get this to work by specifying a constant to be the JSON from the url using node-fetch
const ricp = await fetch('http://ric.pikapools.com/api/stats').then(response => response.json());
and find an object in the JSON using
message.channel.send(ricp.algos.primesr.hashrateString)
Related
Im writing an PWA in Svelte with Routify and im trying to save notes (containing id, title and a body) in a local json file.
Ive been following this code from Svelte REPL (Svelte POST example), but they use an web URL. When trying to use a direct link i get a 404, even tho the path is correct.
<script>
let foo = 'title'
let bar = 'body'
let result = null
async function doPost () {
const res = await fetch('https://httpbin.org/post', {
method: 'POST',
body: JSON.stringify({
foo,
bar
})
})
const json = await res.json()
result = JSON.stringify(json)
}
</script>
<input bind:value={foo} />
<input bind:value={bar} />
<button type="button" on:click={doPost}>
<p>Post it.</p>
</button>
<p>Result:</p>
<pre>
{result}
</pre>
I installed a json server plugin, which kinda worked, but i want to store the data as a local file.
Is it possible to write, using POST to a local json file without using any server?
Is it possible to use relative path when using fetch? Or should i use something else?
Generally, you don't POST data anywhere else but to a server. Having said that, if you absolutely want to save your data using POST, you can add a serviceworker to your app that intercepts the fetch() request and then saves the data in cache, indexeddb, localstorage or something like this. But having that serviceworker in between just for that is a bit silly, you should rather store the data directly in cache, indexeddb or localstorage.
Example for localstorage:
const data = { someKey: { someOtherKey: 'some value' } };
localStorage.setItem('myData', JSON.stringify(data));
Be aware though that, no matter which kind of storage you're using, they all might be wiped out if the user decides to clear browser data or if the browser cleans up by itself due to storage shortage.
Im trying to build an application that fetches data from an web API that returns XML. I want this data in JSON instead, but the API does not support that.
How do i fetch the data and convert it to JSON?
I tried to use xml2js and it seems to work, but i dont understand how to save it as an object so i can use it in my app.
async componentDidMount(){
const url = "this is where the APIurl are";
fetch(url)
.then(res => res.text())
.then(body => parseString(body, function (err, result) {
console.log(result);
})
);
}
result seems to return the data as json, but i cant figure out how to use the data as an object later.
Your best option is to use an external lib to do that. A quick search in google and I found this one https://www.npmjs.com/package/xml-js.
You should also check this question: Convert XML to JSON (and back) using Javascript
To store it on your app you should grab what you need from the parsed XML and put it on the state.
I want to be able to edit JSON then send it through the gulp stream. I know there's gulp-json-edit but I want to understand how it's done and do it myself. In this case, to change the Basic authorization.
For example, something like this:
var data = JSON.parse(fs.readFileSync('./core-config.json'));
data.local.ENDPOINT.CORE.BASIC = "Basic Stuff";
gulp.src(data)
.pipe(somestuff)
.pipe(gulp.dest('./'));
However, this of course doesn't work because data isn't a glob. How can I then manipulate data in a way that I can then pass it to gulp.src()?
A while ago I wrote a module that can turn a regular object stream into a vinyl stream: vinylize. It's mostly useful for static site generation, but If I understand your question correctly it should be able to handle your use case as well.
Your example code using vinylize() would look like this:
var vinylize = require('vinylize');
var data = JSON.parse(fs.readFileSync('./core-config.json'));
data.local.ENDPOINT.CORE.BASIC = "Basic Stuff";
vinylize([data], {
path: 'core-config.json',
contents: JSON.stringify(data),
ignoreSourceProps: true,
})
.pipe(somestuff)
.pipe(gulp.dest('./'));
Blizzard just shut down their old API, and made a change so you need an apikey. I changed the URL to the new api, and added the API key. I know that the URL is valid.
var toonJSON = UrlFetchApp.fetch("eu.api.battle.net/wow/character/"+toonRealm+"/"+toonName+"?fields=items,statistics,progression,talents,audit&apikey="+apiKey, {muteHttpExceptions: true})
var toon = JSON.parse(toonJSON.getContentText())
JSON.pase returns just an empty object
return toon.toSorce() // retuned ({})
I used alot of time to see if i could find the problem. have come up empty. Think it has something to do with the "responce headers".
Responce headers: http://pastebin.com/t30giRK1 (i got them from dev.battle.net (blizzards api site)
JSON: http://pastebin.com/CPam4syG
I think it is the code you're using.
I was able to Parse it by opening the raw url of your pastebin JSON http://pastebin.com/raw/CPam4syG
And using the following code
var text = document.getElementsByTagName('pre')[0].innerHTML;
var parse = JSON.parse(text);
So to conclude I think it is the UrlFetchApp.fetch that's returning {}
So i found the problems:
I needed https:// in the URL since i found after some hours that i had an SSL error
If you just use toString instead of getContentText it works. Thow why getContentText do not work, i am not sure of.
was same problem, this works for me (dont forget to paste your key)
var toonJSON = UrlFetchApp.fetch("https://eu.api.battle.net/wow/character/"+toonRealm+"/"+toonName+"?fields=items%2Cstatistics%2Cprogression%2Caudit&locale=en_GB&apikey= ... ")
I'm using core-ajax to retrieve JSON data just fine. Turning the component around to post back to the server as JSON is another thing altogether. In all cases, and irrespective of the contentType or handleAs parameters passed in, it appears that my JSON object I'm passing in as an input is being converted back to key=value in the server headers.
The code:
var ajax = document.querySelector('core-ajax');
ajax.method = 'POST';
ajax.handleAs = 'JSON';
ajax.contentType = 'application/json';
ajax.params = JSON.stringify(data);
ajax.go();
Really straightforward. The logs in Go give me:
2014/07/22 14:23:09 utils.go:139: OPTIONS /1/users/173?access_token=(token)
2014/07/22 14:23:09 utils.go:124: POST /1/users/173?access_token=(token)
2014/07/22 14:23:09 users.go:379: full_name=Greg%20Johnson
We've verified that there's no transformation happening on our side. Request headers are going out just fine.
I could completely be missing something. How else can we successfully POST out JSON data?
.params is for URL params. What you want is to post the JSON as the request body? For that, I believe you need to set the .body property:
This should do the trick:
ajax.body = data
See https://github.com/Polymer/core-ajax/blob/master/core-ajax.html#L151