How to get JSON from URL in JavaScript?
You can use jQuery .getJSON()
function:
$.getJSON('http://query.yahooapis.com/v1/public/yql?q=select%20%2a%20from%20yahoo.finance.quotes%20WHERE%20symbol%3D%27WRC%27&format=json&diagnostics=true&env=store://datatables.org/alltableswithkeys&callback', function(data) {
// JSON result in `data` variable
});
If you don't want to use jQuery you should look at this answer for pure JS solution.
Get json data from url and put it into variable by JavaScript
You need wrapped your code inside async/await pattern
In your code, you did not return anything.
var tags;
(async () => {
tags = await get()
console.log(tags)
// handle the tags result here
})()
// if you try use tags here it will be undefined
async
return result when it finish and next line of code run immediately so tags variable is undefined
async function get() { let url = 'https://jsonware.com/json/abfe005c41c8214e22e487b8d6eff417.json' let obj = await (await fetch(url)).json(); //console.log(obj); return obj;}var tags;(async () => { tags = await get() //console.log(tags) document.getElementById("tags").innerHTML = JSON.stringify(tags);})()
<div id="tags"></div>
Javascript ES6 Get JSON from URL (no jQuery)
FETCH API
Example:
// url (required), options (optional)
fetch('https://davidwalsh.name/some/url', {
method: 'get'
}).then(function(response) {
}).catch(function(err) {
// Error :(
});
For more information:
https://developer.mozilla.org/en/docs/Web/API/Fetch_API
Getting data from json url
This WOULD have worked if CORS was enabled on their servers. It isn't so you will have to add a proxy, e.g. change
https://rtl2.ods-live.co.uk/api/scheduledJourneys?key=sQ3o5bYbz1&service=&date=2018-08-07&location=039026170002.json
to
"yourserver.com/myproxy.php?url="+encodeURIComponent("https://rtl2.ods-live.co.uk/api/scheduledJourneys?key=sQ3o5bYbz1&service=&date=2018-08-07&location=039026170002.json")
and have yourproxy.php fetch the passed url
This code will give
No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.
$.getJSON("https://rtl2.ods-live.co.uk/api/scheduledJourneys?key=sQ3o5bYbz1&service=&date=2018-08-07&location=039026170002.json", function(myObj) {
var x = "<table border='1'>" for (var o in myObj.data) { x += "<tr><td>" + myObj.data[i].LineRef + "</td>" + "<td>" + myObj.data[o].ScheduledArrivalTime[11] + myObj.data[o].ScheduledArrivalTime[12] + myObj.data[o].ScheduledArrivalTime[13] + myObj.data[o].ScheduledArrivalTime[14] + myObj.data[o].ScheduledArrivalTime[15] + "</td></tr>"; }
x += "</table>" $("#demo").html(x);})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script><p id="demo"></p>
Is there any native function to convert json to url parameters?
Use the URLSearchParams
interface, which is built into browsers and Node.js starting with version 10, released in 2018.
const myParams = {'foo': 'hi there', 'bar': '???'};
const u = new URLSearchParams(myParams).toString();
console.log(u);
How do i fetch json from a url and display json content on my js page
While I can't speak to how the Teams API works, I can help you understand how to render things from a json API in your react component.
In your componentDidMount
function, your example is sending and receiving the response from the API. To render this response, we need to assign the data
to your component's "state" and then use that to render it in HTML.
This will be pretty simple. First, you need to extend your component's state, in a similar manner as you've done for context
. Do this first in the constructor, where we'll declare an initial state of an empty object (I'll name it content
but you can use whatever name makes most sense):
// inside the constructor() function
this.state = {
context: {},
content: {}
}
In React, we use setState
to update this state object state when something changes, like on a lifecycle method such as componentDidMount
. You just need to call this setState
again when you want to change the state object from its initial value to something else. In our case, when we receive the data from the API.
setState
takes whatever you provide it and merges it into the state object, so you only should declare anything you want to change. Anything else not declared will remain unchanged.
So, in componentDidMount
, we can make a small change to do something with data
when it arrives:
componentDidMount() {
fetch('http://example.com/movies.json')
.then(response => response.json())
.then(data => {
this.setState({
content: data
})
});
}
This is basically saying:
- once the component has mounted, make a call to fetch from the API
- then, with that response, take the json from the body
- and then, assign the json "data" into our component's state object under the key of
content
.
You can then do things with this data by calling this.state.content
. I'm not sure what format the data will come in, but whatever json object arrives back from the API will be stored under this.state.content
.
As an example, imagine we get a simple object back from the API that looks like this { title: "Tab title" }
. It means that, on a successful call to the API, our state object will look like this:
{
context: "whatever you have here", // whatever you have here, I don't know this
content: { title: "Tab title" }
}
When this state object is updated, react will trigger a new render of the component.
So, to make it appear in our component, we need to use this state in our render
function (we wrap things in curly braces if they need to be dynamically rendered rather than hardcoded):
render() {
return (
//... the rest of your function
<div>{this.state.content.title}</div>
);
}
As you might have guessed, this will show the title inside a div, if the title exists.
Eventually, you should consider handling the state of the component before that API call has resolved itself. The lifecycle method componentDidMount
will be called after the component is mounted, and because you're hitting an API, there will be something rendered to the DOM before the API call resolves itself. In my example, it'll be just be an empty div, and then it'll appear when the state updates and the render function is called again.
You could do this more effectively by extending your state object to see whether the API response is done (you'd update this in the same place you set the content), and you could render the UI conditionally on this.
The official docs on lifecycle methods will help you understand this pattern more.
Good luck!
Get JSON data from external URL and display it in a div as plain text
You can do this with JSONP like this:
function insertReply(content) {
document.getElementById('output').innerHTML = content;
}
// create script element
var script = document.createElement('script');
// assing src with callback name
script.src = 'http://url.to.json?callback=insertReply';
// insert script to document and load content
document.body.appendChild(script);
But source must be aware that you want it to call function passed as callback parameter to it.
With google API it would look like this:
function insertReply(content) {
document.getElementById('output').innerHTML = content;
}
// create script element
var script = document.createElement('script');
// assing src with callback name
script.src = 'https://www.googleapis.com/freebase/v1/text/en/bob_dylan?callback=insertReply';
// insert script to document and load content
document.body.appendChild(script);
Check how data looks like when you pass callback to google api:
https://www.googleapis.com/freebase/v1/text/en/bob_dylan?callback=insertReply
Here is quite good explanation of JSONP: http://en.wikipedia.org/wiki/JSONP
Related Topics
How to Iterate Through Table Rows and Cells in JavaScript
How to Get Character Array from a String
Node.Js Plans to Support Import/Export Es6 (Ecmascript 2015) Modules
Jquery Xml Error ' No 'Access-Control-Allow-Origin' Header Is Present on the Requested Resource.'
What Do Square Brackets Around a Property Name in an Object Literal Mean
Is There a Better Way to Do Optional Function Parameters in JavaScript
Create Object from Class Name in Javasscript Ecmascript 6
Browsers, Time Zones, Chrome 67 Error (Historic Timezone Changes)
Node.Js on Multi-Core MAChines
How to Use Async/Await at the Top Level
When to Use Setattribute VS .Attribute= in JavaScript
Convert String with Commas to Array
How to Download a File with Angular2 or Greater
Sorting a JavaScript Object by Property Name
What's the Easiest Way to Call a Function Every 5 Seconds in Jquery