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>
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>
How to access a JSON array directly from url
You can use jQuery getJSON()
function :
$.getJSON(' localhost:8080/dataurl', function(data) {
//data is the JSON string
var jsonObj = JSON.parse(data);
});
Now, Below are the methods to parse the jsonObj
to get the state1
.
Using array map()
method :
var jsonObj = [ { "year":2015, "month":4, "day":1, "num":0, "time":"2015-04-01", "hour":0, "zone":3, "state1":2137, "state2":249, "state3":1810, "state4":30, "state5":0 }, { "year":2016, "month":12, "day":1, "num":0, "time":"2015-04-01", "hour":0, "zone":3, "state1":2474, "state2":250, "state3":1811, "state4":31, "state5":0 } ];
var state1arr = jsonObj.map(function(item) { return item.state1;});
console.log(state1arr);
How to read JSON file from URL and assign it into a global variable in NodeJS?
Technically to make it a global variable you just need to define it outside of your callback function.
var url = 'https://myurl.com/file.json';
var jsonObject;
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
jsonObject = JSON.parse(body);
console.log(jsonObject);
}
});
However, based on what I can see here I don't think that will solve whatever problem you're trying to solve. The reason is that request's callback is handled asynchronously. So even if you assign that to a global variable it won't be accessible in your other code later down the line.
var url = 'https://myurl.com/file.json';
request(url, function (error, response, body) {
if (!error && response.statusCode == 200) {
var jsonObject = JSON.parse(body);
// Rest of your application that needs access to jsonObject can do here...
// You can also pass it on to another function by running something like `processResponse( jsonObject )`;
}
});
How to get JSON Object from URL
The question is, is this domain (api.locu.com) the same from where you serve your files? I suppose it isn't. In this case, you have two options:
- Your backend can proxy the request from this site
- You have to use a JSONP object if it's supported by the API
ReactJS - get json object data from an URL
Edit: Use fetch for making API calls.
fetch(http://www.example.com/api/json/x/a/search.php?s=category)
.then(response => response.json())
.then((jsonData) => {
// jsonData is parsed json object received from url
console.log(jsonData)
})
.catch((error) => {
// handle your errors here
console.error(error)
})
Fetch is available in all modern browsers.
Related Topics
Convert Stdclass Object to Array in PHP
Disable PHP in Directory (Including All Sub-Directories) With .Htaccess
How to Insert Multiple Rows from a Single Query Using Eloquent/Fluent
Incorrect Integer (2147483647) Is Inserted into MySQL
$_Server['Http_Referer'] Missing
Send Value of Submit Button When Form Gets Posted
Filter Multidimensional Array Based on Partial Match of Search Value
How to Get Real Ip from Visitor
What Is Function Overloading and Overriding in PHP
Remove Portion of a String After a Certain Character
Convert Number to Month Name in PHP
Create or Write/Append in Text File
PHP Multiple Delimiters in Explode
Header and Footer in Codeigniter
PHP Variable in HTML No Other Way Than: ≪PHP Echo $Var; ≫