Showing JSON in html with javascript - html

i am new with JSON. I am using a api which using JSON for response. I am calling the api url by simple xhr method. The code is working and i am getting 200 status but
how do i able to retrieve the JSON in the html?
I was able to show the JSON by printing xhr.responseText in innerHTML. But i need to show the data so i can use them in html.
Can you suggest how i can present the data in html when i have the json data in xhr.responseText.
Please let me know if you need more info.
Can anyone guide me how to do it via jquery also?

If you add JSON2.js (from https://github.com/douglascrockford/JSON-js/blob/master/json2.js) to your page, then you can parse the JSON into a JavaScript object by using:
var parsedData = JSON.parse(xhr.responseText);
If you completely trust your JSON source, you can also do it very quickly and without using JSON2.js by simply evaling it thus:
var parsedData = eval('(' + xhr.responseText + ')');
but this will run any code embedded in the response and so isn't secure and generally wouldn't be recommended.

here is another post which works and less code because of jquery. The first answer works perfectly. I thought this might be help for people who having same problem.
Trying to use jQuery to display JSON text data

Related

use JSON api for live news

I have this Fox Sport API url :
https://newsapi.org/v1/articles?source=fox-sports&sortBy=top&apiKey=955acf3993df49169dfa33dce76d015f
How do i use this? I know it's based on Json. But where do i put this URL? in what format or file? Can someone please help me?
I alrady tried putting it between scripts tags in my index.php file but no results...
Thank you!
Google it ---> Php curl. Read the doc!
If you are using a framework, let us know which one😃
JSON is simply a useful way to send and receive strings that represent objects in JavaScript. In these days I'm working on an application that uses JSON strings to store and retrieve data, and I found a very simple way to get data from JSON strings, that is jQuery. This library has a jQuery.getJSON() method, which let you to load JSON-encoded data from the server (or locally) using a GET HTTP request. Here you can find all the details you need to use this method.
Obviously you could choose not to use any third-part library and do what you need in vanilla JavaScript, but jQuery is very useful since it helps to avoid common cross-browser issues.
In my application I store data from a JSON string in this way:
var placesList;
jQuery.getJSON("places.txt").done(function (data) {
placesList = data;
});
that is using an external variable to store them using an anonymous function. As you can see, my URL here is places.txt, but you can use any valid URL you want that provide a JSON string.
You should try like this -
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
var url = 'https://newsapi.org/v1/articles?source=fox-sports&sortBy=top&apiKey=955acf3993df49169dfa33dce76d015f';
$.getJSON(url).then(function(res){
console.log(res) //{status: "ok", source: "fox-sports", sortBy: "top", articles: Array[10]}
console.log(res['status']) //ok
console.log(res['source']) //fox-sports
console.log(res['sortBy']) //top
console.log(res['articles'].length) //10
})
})
</script>

Angular and JSON, having trouble parsing for ng-repeat

I'm horribly sorry if there is a post for this, I tried to search but didn't find a answer.
Problem:
I'm calling a web service and receiving not so well formed JSON data from a Dynamics Nav service:
JSON:
"[{\"type\":\"2\",\"number\":\"VHT3866\",\"location\":\"Delta\",\"destinationNo\":\"\",\"contactName\":\"Jesus\",\"shipToName\":\"Lord jesus\",\"highPriority\":\"false\",\"hasComment\":\"true\",\"assignedTo\":\"\",\"source\":\"\"},{\"type\":\"2\",\"number\":\"VHT3866\",\"location\":\"Delta\",\"destinationNo\":\"\",\"contactName\":\"Jesus\",\"shipToName\":\"Lord jesus\",\"highPriority\":\"false\",\"hasComment\":\"true\",\"assignedTo\":\"\",\"source\":\"\"}]"
I then take this JSON and use angular.fromJson(json) to get it properly.
It doesn't seem to change into an array of javascript objects, but just plain text.
However if I take the same JSON and just put it manually in like this:
var json = angular.fromJson(stringfromserver);
It turns into a proper javascript object and ng-repeat throws no error.
I found an answer on Quora:
--- Le Batoure,
Angular from json is now strict so assuming that this string is from a trusted source you would have to use "eval()" plus surround the call in parenthesis for it to work
var hatsData = angular.fromJson(eval("(" + hats + ")"))
If you bring your JSON from http request for example you don't need to use the fromJson method.
The JSON is automatically parsed by Angular and you can use it directly.

SAPUI5 oModel.getJSON() isn't working when I use a JSON file as origin

I created my Model using a JSON file.
var oModel = new sap.ui.model.json.JSONModel( jsonFileUrl ); //JSON from file
It worked and the element was populated as I wanted.
But after this, when I tried to use oModel.getJSON() to get the JSON data it didn't work.
If I use an variable with the same content as the file, it works!
You can check the full test that I created:
https://googledrive.com/host/0B2gJUv6a_V1dYnNSV0ZsTFhxazg/index.html
Is there anybody to help me to understand what on Earth is happening here?
It's because at the time you try to emit the JSON here:
$("#jsonFile").append(oModelFile.getJSON());
the actual ajax request to retrieve the file hasn't completed, and so the JSON model isn't filled at that time.
Wrap this in a handler for the requestCompleted event like this and it will work:
oModelFile.attachRequestCompleted(function() {
$("#jsonFile").append(oModelFile.getJSON());
});

Pass Json Object from Play! framework to HighCharts JS

http://www.playframework.com/documentation/2.1.x/JavaTodoList
Using the above tutorial as a reference, I have created an application which sends data from the model to view via the Application controller.
I have managed to display the model(Tasks) as a high chart. The code is here.
public static Result format(){
return ok(views.html.frmt.render("Visualize it",Task.all()));
}
This goes to this view page.
http://ideone.com/ycz9ko
Currently, I use scala templating inside the javascript code itself. Refer to lines 9-14 and lines 20-24.This unelegant style of doing things is not really optimal.
I want to be able to accomplish the above using Json instead.
public static Result jsonIt(){
List<Task> tasks = Task.all();
return ok(Json.toJson(tasks));
}
My Qns are how to send the JSON objects to a view template.
And how to parse it into a Highcharts format. Is there some standard procedure to do this ? Or else I have to write my own method to do this ?
It'll great if someone can show me a code snippet. Also I would prefer a post not using Ajax. I would just want to know how to do this first.
I also found this stackoverflow post useful.how to parse json into highcharts. However, it didnt answer the part about converting from Play format to Highcharts format.
Thanks in advance
You don't need to pass a json object to your template, instead you might do an ajax call from your client side javascript (your template) and get json response that you could use futher in javascript code to build a chart. For example :
You have some path that is bind to your controller jsonIt() like so /chartsdata/json
then using jquery shorthand for ajax request:
var chart_data = $.get('/chartsdata/json', function(data) {
return data;
});
now you can use a chart_data that is an array of objects where each object represents a Task, in your further javascript code to build a chart.

Google dictionary api does not return pure json?

I have the following code:
var json = new WebClient().DownloadString(string.Format(#"http://www.google.com/dictionary/json?callback=dict_api.callbacks.id100&q={0}&sl=en&tl=en", "bar"));
This returns something like this:
dict_api.callbacks.id100({"query":"bar","sourceLanguage":"en","targetLanguage":"en","primaries":[{"type":"headword","terms":[{"type":"text","text":"bar",....
Why is it returning a function rather than just the json? Am I using web client incorrectly?
As I understand it, this is JSONP - JSON which is "padded" with a function call to allow cross-domain data transfer. I strongly suspect that if you pass in a different callback name on the URL, you'll see that other name come back in the response.
(Note that although I work for Google, this answer is not an "official" response from Google in any way, shape or form.)
You may want to use check this out :
json_decode for Google Dictionary API
They actually modify the resultant jsonp to get a json