referencing an unnamed javascript object in a JSON file - javascript

I am referencing a JSON file through a web service. The file contains an unnamed object. How do I refer to the object?
I am referencing the file like any normal JSON file
<script src="http://somewebservice.com/object.json"></script>
object.json
{
"one":1,"two":2,"three":{
"one":1,"two":2
}
}
Do I really need to use JSON.parse()? It's already in a JSON file format.

JSON is format that uses human-readable text to transmit data objects, so if "referencing a JSON file through a web service" means you get it as String in HTTP response, then yes, you have to use JSON.parse() to get javascript object from the string.

Loading your data using <script src="http://somewebservice.com/object.json"></script> will leave you with no handle to the loaded resource.
Either use JSONP or, if a cross-origin policy is place, load the resource using some ajax mechanism.
Using fetch
fetch("http: //somewebservice.com/object.json").then(function (res) {
try {
console.log(JSON.parse(res));
}
}).catch(console.error);

I ended up using AJAX to retrieve the remote file.
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var objects=JSON.parse(this.responseText);
console.log(objects);
}
};
xhttp.open("GET", "http://somewebservice.com/object.json", true);
xhttp.send();

Related

Read CSV File From Sharepoint Using XMLHttpRequest

For some context, I'm looking to read a csv file that is stored on a sharepoint - and I'm looking to do this from the frontend (a vue component) of my vue web application, and display it on that vue.
This post was really helpful
However, I don't make use of jquery anywhere in the application and only need to read the csv file in one part of my code. Therefore, I was wondering how I can go about implementing this with just the XMLHttpRequest API as opposed to jquery's AJAX?
I am not sure I understood your question completely, but here is what I think might be the answer:
using XMLHttpRequest():
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// Typical action to be performed when the document is ready:
document.getElementById("demo").innerHTML = xhttp.responseText;
// in here you basically manipulate your dom with fetched data or call on functions.
}
};
xhttp.open("GET", "yourApiUrl", true);
xhttp.send();
JSON:
let url = 'https://example.com';
fetch(url)
.then(res => res.text())
.then(out =>
console.log('My data here', out))
.catch(err => throw err);
JSON is Like XML Because
Both JSON and XML are "self describing" (human readable)
Both JSON and XML are hierarchical (values within values)
Both JSON and XML can be parsed and used by lots of programming languages
Both JSON and XML can be fetched with an XMLHttpRequest
JSON is Unlike XML Because
JSON doesn't use end tag
JSON is shorter
JSON is quicker to read and write
JSON can use arrays
The biggest difference is:
XML has to be parsed with an XML parser. JSON can be parsed by a standard JavaScript function.
Why JSON is Better Than XML
XML is much more difficult to parse than JSON.
JSON is parsed into a ready-to-use JavaScript object.
Source: W3School

Reading JSON format from URL

I am trying to make a website that analyzes data from a game called Overwatch.
I have this (https://enhanced-ow-api.herokuapp.com/ShalevBito-2753/competetive/pc/us/) and when you visit it, all you see is text in the json format.
Is there anyway I can read this using JavaScript and send it to a nice <p> tag on my website?
Current Code:
<script>
var obj = JSON.parse('https://enhanced-ow-api.herokuapp.com/ShalevBito-2753/competetive/pc/us/');
document.getElementById("elims").innerHTML = obj.Eliminations;
</script>
<p id="elims"></p>
You didn't tag this with jQuery so I'm going to assume you're wanting to do this with vanilla JS. .jsonParse() doesn't actually request JSON from a URL--it parses existing JSON-data into an object.
To handle this, you'll first want to request the data. This can be done using an XMLHttpRequest():
var requestUrl = "https://enhanced-ow-api.herokuapp.com/ShalevBito-2753/competetive/pc/us/";
You next want to build out and perform your request. Create a function once the JSON data is fully loaded (onload):
let request = new XMLHttpRequest();
request.open('GET', requestUrl);
request.responseType = 'json';
request.send();
request.onload = function() {
logData(request.response);
}
An example function that handles the data could be:
function logData(data) {
document.querySelector('.elims').innerText = `Genji Eliinations: ${data['Genji']["Combat"]["Eliminations"]}`;
}
This appends it to an element with the class .elims, for example, a tag:
<p class="elims"></p>
I've added the whole code below. This should be enough to get you in the correct direction:
let requestUrl = "https://enhanced-ow-api.herokuapp.com/ShalevBito-2753/competetive/pc/us/";
let request = new XMLHttpRequest();
request.open('GET', requestUrl);
request.responseType = 'json';
request.send();
request.onload = function() {
logData(request.response);
}
function logData(data) {
document.querySelector('.elims').innerText = `Genji Eliinations: ${data['Genji']["Combat"]["Eliminations"]}`;
}
<p class="elims">
</p>
Good way to start, so the URL you are trying to access is the REST web service which is just a GET method which produces the JSON. All you have to do is make an AJAX call via Javascript or Jquery and you can parse this to a Javascript variable then you can use those variable values you can generate the Paragraph elements to your HTML page.
You need to load data from server using HTTP GET request like this,
$.get( "https://enhanced-ow-api.herokuapp.com/ShalevBito-2753/competetive/pc/us/", function( data ) {
console.log(data);
//process your data here
});
Since your url (https://enhanced-ow-api.herokuapp.com/ShalevBito-2753/competetive/pc/us/) is in json format. In order to retrieve it you need to use something like getJson.
Example:
$.getJSON( "https://enhanced-ow-api.herokuapp.com/ShalevBito-2753/competetive/pc/us/", function( json ) {
console.log( "JSON Data: " + json.Assists["Healing Done"]);
});
You can read more on how to use getJson.

uploading pdf/doc etc and sending data to the server in request - Javascript

I need to upload pdf,excelsheets,doc. etc format to server - data in request file using simple Javascript.
I was thinking to do with Blob , byte stream .. is it possible.
Can someone explain ?
Using vanilla Javascript you can create an XMLHTTPRequest object and send the file to any endpoint of your choice.
Some questions to consider when you are working doing this:
Are you looking to upload just the file or do you need to upload any associated data with it?
Do I need to support multiple files? If so, you could use the FormData object (it is a defined key value pair type) to hold multiple files if you have an HTML5 input form with the multiple attribute set. Make sure your project allows support for it.
What server/framework are you using? How do you access this? A request object? Something similar?
How do you want/need to create a selector for your html file input for use with Javascript? I'll provide an example of using the html attribute of id below.
Do you need to support CORS? Essentially, are you sending a request to the same server or a remote server? If remote, you'll need to configure CORS in your server.
file input that allows multiple file support
<input type='file' id='multiple-file-input' multiple>
javascript example
// idElementForFiles - id of the <input type="file" multiple>
// endpoint - URL to send your request to
var idElementForFiles = 'multiple-file-input';
var endpoint = '/path_to_server/request';
var formdata = new FormData(); // Create FormData
var uploadedFiles = document.getElementById(idElementForFiles); // set our uploadedFiles variable
// Iterate through each file in uploadedFiles
for (i = 0; i < uploadedFiles.files.length; i++) {
// Appending each file to FormData object
// sending to 'endpoint' as an array of {'name_of_file': 'binary_file_data'}
formdata.append(uploadedFiles.files[i].name, uploadedFiles.files[i]);
}
// create new Ajax call and send
var xhr = new XMLHttpRequest();
xhr.open('POST', endpoint);
xhr.send(formdata);
xhr.onreadystatechange = function () {
if (xhr.readyState == 4 && xhr.status == 200) {
console.log(xhr); // log response object
}
}

Get JSON in a Chrome extension

Small problem with my chrome extension.
I just wanted to get a JSON array from another server. But manifest 2 doesn't allow me to do it. I tried specify content_security_policy, but the JSON array is stored on a server without SSL cert.
So, what should I do without using manifest 1?
The CSP cannot cause the problem you've described. It's very likely that you're using JSONP instead of plain JSON. JSONP does not work in Chrome, because JSONP works by inserting a <script> tag in the document, whose src attribute is set to the URL of the webservice. This is disallowed by the CSP.
Provided that you've set the correct permission in the manifest file (e.g. "permissions": ["http://domain/getjson*"], you will always be able to get and parse the JSON:
var xhr = new XMLHttpRequest();
xhr.onload = function() {
var json = xhr.responseText; // Response
json = json.replace(/^[^(]*\(([\S\s]+)\);?$/, '$1'); // Turn JSONP in JSON
json = JSON.parse(json); // Parse JSON
// ... enjoy your parsed json...
};
// Example:
data = 'Example: appended to the query string..';
xhr.open('GET', 'http://domain/getjson?data=' + encodeURIComponent(data));
xhr.send();
When using jQuery for ajax, make sure that JSONP is not requested by using jsonp: false:
$.ajax({url:'...',
jsonp: false ... });
Or, when using $.getJSON:
$.getJSON('URL which does NOT contain callback=?', ...);

Using AJAX to access to the Twitter API

I'm thinking about adding some twitter functions in my web-application, so I started doing some tests. I checked the way to call the search twitter URL (more info in: http://dev.twitter.com/doc/get/search) in order to get tweets that contains the searched word/sentence. I realized that you can do it in php just getting the JSON file that the search URL returns with the file_get_contents() function. Also you can do it directly in JavaScript creating a script object, appending it to the body and use the callback parameter of the search URL to process the data.
Different ways to do, but that's the way I finally did it:
MAIN HTML FILE:
<title>Twitter API JSON</title>
<script type="text/javascript">
//function that created the AJAX object
function newAjax(){
var xmlhttp=false;
try {
xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
} catch (E) {
xmlhttp = false;
}
}
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
xmlhttp = new XMLHttpRequest();
}
return xmlhttp;
}
//function that search the tweets containing an specific word/sentence
function gettweets(){
ajax = newAjax();
//ajax call to a php file that will search the tweets
ajax.open( 'GET', 'getsearch.php', true);
// Process the data when the ajax object changes its state
ajax.onreadystatechange = function() {
if( ajax.readyState == 4 ) {
if ( ajax.status ==200 ) { //no problem has been detected
res = ajax.responseText;
//use eval to format the data
searchres = eval("(" + res + ")");
resdiv = document.getElementById("result");
//insert the first 10 items(user and tweet text) in the div
for(i=0;i<10;i++){
resdiv.innerHTML += searchres.results[i].from_user+' says:<BR>'+searchres.results[i].text+'<BR><BR>';
}
}
}
}
ajax.send(null);
} //end gettweets function
</script>
#search_word Tweets
<input type="button" onclick="gettweets();"value="search" />
<div id="result">
<BR>
</div>
</html>
PHP WHERE WE GET THE JSON DATA:
$jsonurl = "http://search.twitter.com/search.json?q=%23search_word&rpp=10";
$json = file_get_contents($jsonurl,0,null,null);
echo $json;
And that's it, in this way it works fine. I call the PHP file, it returns the JSON data retrieved from the search URL, and in the main HTML JavaScript functions I insert the tweets in the div. The problem is that at the first time, I tried to do it directly in JavaScript, calling the search URL with Ajax, like this:
MAIN HTML FILE:
//same code above
//ajax call to a php file that will search the tweets
ajax.open( 'GET', 'http://search.twitter.com/search.json?q=%23search_word&rpp=10', true);
//same code above
I thought it should return the JSON data, but it doesn't. I'm wondering why not and that is what I would like to ask. Does someone have any idea of why I can't get JSON data using the Ajax object? If the search URL http://search.twitter.com/search.json?q=%23search_word&rpp=10 returns JSON data, it should be obtained in the ajax object, right?
XHR requests are generally limited to same-domain requests; e.g, if you're on bertsbees.com, you can't use an Ajax method to pull data from twitter.com.
That said, Twitter's API supports a popular data transport method known as JSON-P, which is really just a glorified injection technique. You simply pass it a callback method, and the data returned will be wrapped in your desired function, so it gets eval'd and passed in.
You cannot make a cross domain request using javascript, unless you are doing from an browser addon.

Categories

Resources