Jump to content

Display Json Data?


paulmo

Recommended Posts

How to print JSON data? Thanks.

<script type="text/javascript">var req = new XMLHttpRequest();req.open("GET", "file:///home/web/test.json", /*async*/true);req.onreadystatechange = myHandler;req.send(/*no params*/null);function myHandler() {   if (req.readyState == 4 /*complete*/) {	   var menuField = document.getElementById('menu');	   var card = eval('(' + req.responseText + ')');	   menuField.value = card.menu[0].value;   }}</script>

test.json:

{"menu": {  "id": "file",  "value": "File",  "popup": {    "menuitem": [	  {"value": "New", "onclick": "CreateNewDoc()"},	  {"value": "Open", "onclick": "OpenDoc()"},	  {"value": "Close", "onclick": "CloseDoc()"}    ]  }}}

Link to comment
Share on other sites

you can view the ajax response data with: alert(req.responseText) to access the text "New" you would need:

card.menu.popup.menuitem[0].value

if the html element with id 'menu' is a <ul> tag, maybe your after this:

var lis = document.getElementById('menu').getElementsByTagName('li');for (var i=0, j=lis.length; i<j; i++) {    lis[i].innerHTML = card.menu.popup.menuitem[i].value;}

Link to comment
Share on other sites

Thanks JamesB, check out revision please, simplified. I've read Crockford's JSON articles but those tutorials (pretty much any on this subject) are beyond my comprehension. In Firebug, the get responseText is showing my json.test data, but that alert you gave me just pops up empty.json.text

{	"futures":		{			"ES":				[					{"index": "s&p"},					{"volume": "5"},					{"volatility": "moderate"}				]			"CL":				[					{"index": "oil"},					{"volume": "4"},					{"volatility": "high"}				]		} }

<script type="text/javascript">//JSON testingvar req = new XMLHttpRequest();req.open("GET", "file:///home/web/test.json", /*async*/true);req.onreadystatechange = myHandler;req.send(/*no params*/null);  function myHandler() {   if (req.readyState == 4 /*complete*/) {	   var menuitemField = document.getElementById('futures');	   var futures = eval('(' + req.responseText + ')');	   futures[0].value   }} alert(req.responseText) var lis = document.getElementById('futures').getElementsByTagName('li');for (var i=0, j=lis.length; i<j; i++) {	lis[i].innerHTML = futures[i].value;}</script> <div id="futures"><ul></ul></div>

I'm also trying this, from Mozilla website, which seems simpler. This doesn't throw any alert window, but again the get responseText json data is showing in Firebug.

<script type="text/javascript">//JSONvar request = new XMLHttpRequest();  request.open('GET', 'file:///home/web/test.json', false);  request.send(null);  if (request.status == 0)  console.log(request.responseText);   alert(request.responseText); var lis = document.getElementById('futures').getElementsByTagName('li');for (var i=0, j=lis.length; i<j; i++) {	lis[i].innerHTML = futures[i].value;}</script> <div id="futures"><ul></ul></div>

I just want to display the data on the page! Ultimately I want to use dynamic url sources as JSON data, but I've got to get this figured out first, real simple, from a file. Thanks in advance.

Link to comment
Share on other sites

the alert(req.responseText) needs to go inside the if condition in myHandler().

function myHandler() {if (req.readyState == 4 /*complete*/) {alert(req.responseText)

also are you sure ajax works with the file:// protocol? i've never tested that.if you're running a local web server, try using 127.0.0.1, eg. "127.0.0.1/test.json"

Link to comment
Share on other sites

Thanks James, alert shows the json data! But only with alert(require.responseText) outside of the function/if statement...how to get json data on the page in the div?

<script type="text/javascript">//JSONvar request = new XMLHttpRequest();request.open('GET', 'file:///home/web/test.json', false);  request.send(null);function myHandler() {if (request.status == 0)console.log(request.responseText);}alert(request.responseText);var lis = document.getElementById('futures').getElementsByTagName('li');for (var i=0, j=lis.length; i<j; i++) {	lis[i].innerHTML = futures[i].value;}</script> <div id="futures"><ul></ul></div>

to your question, yes XMLHttpRequest works with files...from Mozilla:

Despite its name, XMLHttpRequest can be used for non-HTTP requests. This example shows how to use it to fetch a file from the local file system. view plainprint?
  1. var request = new XMLHttpRequest();
  2. request.open('GET', 'file:///home/user/file.json', false);
  3. request.send(null);
  4. if (request.status == 0)
  5. console.log(request.responseText);

Link to comment
Share on other sites

oh awesome, thanks for that! try changing this:

var lis = document.getElementById('futures').getElementsByTagName('li');for (var i=0, j=lis.length; i<j; i++) {lis[i].innerHTML = futures[i].value;}

to this:

var ul = document.getElementById('futures').getElementsByTagName('ul')[0];var liObjects = card.menu.popup.menuitem;var li;for (var i=0, j=liObjects.length; i<j; i++) {li = document.createElement('li');li.innerHTML = liObjects[i].value;ul.appendChild(li);}

i don't think you need a handler function for non async requests, the send() call probably just blocks until the request is complete or fails. also you'll probably need to put the whole javascript code in a window.onload = function() { /* here */ }, so that the browser reads this html first:

<div id="futures"><ul></ul></div>

Link to comment
Share on other sites

thanks, but these are no longer in json file:

var liObjects = card.menu.popup.menuitem;

this is:

{	"futures":		{			"ES":				[					{"index": "s&p"},					{"volume": "5"},					{"volatility": "moderate"}				]			"CL":				[					{"index": "oil"},					{"volume": "4"},					{"volatility": "high"}				]		} } 

so

var liObjects = futures;

is not working.

Link to comment
Share on other sites

ok. is this a new json file than from the beginning? so are you asking how to access properties of the new object returned? Do you know how objects work? It's not hard. everything is just properties and values. if you have an object like this:

var person = {  name : 'me',  age	:  20};alert(person.name) //alerts mealert(person.age) //alerts 20

Link to comment
Share on other sites

scientist yes I would be asking how to process properties of object returned. your example gives static info in variable on page, but mine is coming from another file, and I don't know how to declare that data in a variable. I'm not just writing static values in a variable to repeat it back, rather attempting to use json or any other external data source to do the populating, not me writing it in each line. I've added json.parse after the if (request.status == 0) console.log(request.responseText);thinking that might help, but this or any combination of it does not throw alert:

var jparse = JSON.parse(request.responseText);}alert(jparse.futures.ES);

Link to comment
Share on other sites

Ok that clears it up a bit, wasn't clear what you were having problems with. What you need to do is use eval to turn the responseText into json so you can access it like an object and use its properties. You want to do this after the lines that have successfully alerted/logged request.responseText.

var futures = eval('(' + request.responseText + ')');alert(futures.ES.index);alert(futures.CL.index);

Link to comment
Share on other sites

thanks...those aren't throwing alerts...I've tried without .index as well. and tried both eval() and JSON.parse() which is recommended in the standard. any further help is appreciated.

window.onload = function(){var request = new XMLHttpRequest();  request.open('GET', 'file:///home/web/test.json', false);   request.send(null);  function myHandler() {if (request.status == 0)  console.log(request.responseText);var futures = JSON.parse('(' + request.responseText + ')');}alert(futures.ES.index);alert(futures.CL);//alert(request.responseText);var ul = document.getElementById('futures').getElementsByTagName('ul')[0];var liObjects = futures.ES;var li;for (var i=0, j=liObjects.length; i<j; i++) {li = document.createElement('li');li.innerHTML = liObjects[i].value;ul.appendChild(li);    }}</script><div id="futures"></div>

Link to comment
Share on other sites

what do you get for output in the console if you

console.log(request.responseText);

and

 [color=#000088]var[/color][color=#000000] futures [/color][color=#666600]=[/color][color=#000000] JSON[/color][color=#666600].[/color][color=#000000]parse[/color][color=#666600]([/color][color=#008800]'('[/color][color=#000000] [/color][color=#666600]+[/color][color=#000000] request[/color][color=#666600].[/color][color=#000000]responseText [/color][color=#666600]+[/color][color=#000000] [/color][color=#008800]')'[/color][color=#666600]);[/color]

in a good conole, like Chrome or firebug. edit: saw you edit. are you seeing any output from request.responseText?

Link to comment
Share on other sites

no errors in FB console, and alert(request.responseText) pops up the json.test contents. section after function myHandler...problem somewhere in here as far as not displaying json/array/list on page (tried eval as well):

var futures = JSON.parse(request.responseText);var ul = document.getElementById('futures').getElementsByTagName('ul')[0];var liObjects = futures; var li;for (var i=0, j=liObjects.length; i<j; i++) {li = document.createElement('li');li.innerHTML = liObjects[i].value;ul.appendChild(li);	}} </script> <div id="futures"></div>

Link to comment
Share on other sites

well first of all, are you sure futures is logging/alerting after you eval or parse it? You konw it's coming in right, but it's probably just text. You should really see it in the console. because a good console will give away it's type too. For instance logging an array would log every element in the array with little pull down tabs. Same for objects. extremely useful for debugging. but lets look at your json structure first.

{	"futures":		{			"ES":				[					{"index": "s&p"},					{"volume": "5"},					{"volatility": "moderate"}				]			"CL":				[					{"index": "oil"},					{"volume": "4"},					{"volatility": "high"}				]		} }

futures is an object, with two objects in it, and the value of each of those objects is an array of objects. You are trying to run a for loop on an array.
var futures = JSON.parse(request.responseText);var liObjects = futures;var li; for (var i=0, j=liObjects.length; i<j; i++) {}</script>

for example, to alert the value oil, this would be what you need to do.
alert(futures.CL[0].index);

to print out the values of the ES array

for(var i = 0, l = futures.ES.length; i < l; i++){  for(var key in futures.ES[i]){    alert(futures.ES[i][key];  };};

you need think of what you actually need from futures and understand the differences on how to iterate over an object vs. over an array to get it.

Link to comment
Share on other sites

getting closer it seems. first, window.onload prevents good things happening, so commented out below. eval() also prevents good things, while JSON.parse() is delivering. not sure why that is. so the good things are 1) "futures" is in left menu under DOM tab of firebug, with corresponding Object {futures = Object} displayed and all data (ES, CL etc.) in the drop-downs (how to copy/paste firebug screens??) also under "futures" menu, i is 0, ix is -1, and key and l are undefined. all this only happens with JSON.parse 2) in DOM left menu, "request" appears with corresponding XMLHttpRequest info (responseText, get Upload etc.) all appearing in dropdowns. so seems things are moving in right direction, but list still not appearing on page, and those list alerts are not working. thanks in advance for yet more help/direction.

<script type="text/javascript">//window.onload = function()//{var request = new XMLHttpRequest();  request.open('GET', 'file:///home/web/test.json', false);  request.send(null);  function myHandler() {if (request.status == 0)  console.log(request.responseText);} //alert(request.responseText); //works //'(' + request.responseText + ')' this is for eval //alert(futures.CL[0].index); not working//alert(futures.CL); var futures = JSON.parse(request.responseText); for(var i = 0, l = futures.ES.length; i < l; i++){  for(var key in futures.ES[i]){	alert(futures.ES[i][key]);  };};</script>

Link to comment
Share on other sites

then you need to get back to basics and figure out why responseText is not showing up. As far as I know, just because it is in a file called .json, does not automatically make it JSON. It's all just text, so you are right that a conversion process needs to happen in order to turn into a legitImate structure in javascript. If you are changing things around, that's probably not helpful and might be confusing you. So my recommendation is to step back and think about it again and start a simple test case. For now, just create a simple script that makes the request to get the file and log the response. Have nothing else but that code. Make sure you can make the request, get into a variable, and then log that variable. At this point it should still be a string. THEN convert it into a Javascript structure and then log that, and confirm that in the console, so you know it's an object. Then try and log a specific value, like oil. Come back with where you get stuck with ONLY this specific test code, so that way we can follow along and try it too. The point is to find the most simplest steps possible to get your desired outcome, which makes it easier for us to reproduce so we can help you too. After it works, then you can plug back into the greater context of your application. if you feel like that is a lot, then you have to realize it's all part of programming. This is how I do it at work all the time. I figure out what I need to do as a whole, and then build it one piece at a time. After the first piece works without any bugs/issues, onto the next one, and so on so forth until it's all working together.

Link to comment
Share on other sites

I'm going to try and run this myself, but first thing I notice is your JSON is invalid. You need a comma after the curly brace before CL. You can verify it too by going herehttp://jsonlint.com/

Link to comment
Share on other sites

hokey. I kept getting errors using the file protocpl, but using normal conventions to get the file, I was able to get it to work. this assumes the code and the json files are in the same directory. In outputting the content, I neglected to take into consideration there was a futures object being returned, so there was an extra level of nesting that I handled that you will see in the parsing of the responseText. json

 {  "futures": {	 "ES": [{"index": "s&p"},			{"volume": "5"},			{"volatility": "moderate"}],	 "CL": [{"index": "oil"},			{"volume": "4"},			{"volatility": "high"}]  }}

html/js

 <html><head><script>window.onload = function() {console.log('ENTER window.onload');  var futures = {};  var json = {};  var output = document.getElementById('output');  var request = new XMLHttpRequest();     request.open('GET', 'futures.json', false);    request.send(null);      if(request.status == 200){	console.log(request.responseText);	//json = eval('(' + request.responseText + ')');  //this works too	json = JSON.parse(request.responseText);	futures = json.futures;	console.log(futures);  };   for(var i = 0, l = futures.ES.length; i < l; i++){	 for(var key in futures.ES[i]){	   output.innerHTML += futures.ES[i][key] + '<br/>';	 };  };};</script><body><h3>This is a test</h3><p id="output"></p></body></html>

Link to comment
Share on other sites

awesome! thanks scientist! only works with this though (tried === also with 200):

if(request.status == 0){

maybe because I'm not running this from localhost?some questions please so I can understand:

  • please explain
    console.log('ENTER window.onload');

    because that solved window.onload problem.

  • do you define var futures and json with empty brackets just to keep your code clean so you don't have to to put a var on them in the if statement?
  • how to display key values on page in groups, like 0, 1, 2 for one index, then the other, not 0, 0, 1, 1, 2, 2?

you've helped me out a lot, so even if you could just throw some terms at me to get me started I can go googling :google_lt:

Link to comment
Share on other sites

awesome! thanks scientist! only works with this though (tried === also with 200):
if(request.status == 0){

maybe because I'm not running this from localhost?some questions please so I can understand:

  • please explain
    console.log('ENTER window.onload');

    because that solved window.onload problem.

That didn't do anything to solve that problem. You had some of your code in a myHandler function, I think it was? I don't know what you were doing with that, so I took it out. I just let everything run sequentially since your AJAX is running synchronously.
  • do you define var futures and json with empty brackets just to keep your code clean so you don't have to to put a var on them in the if statement?

Yes, it's just my habit for how I like to code. I like to be very particular about my variables and their potential to be easily leaked into the global scope. Anytime i need to make a variable other than for a loop, I like to declare it at the top of my functions/methods. I think it keeps it more organized and easier to read. The var's are distracting to me halfway down a function when I'm trying to read it. I like to assume I already know everything I need to read/debug a function just by reading it's name, params, and the names of the variables it is using. Like I said, just a personal habit.
  • how to display key values on page in groups, like 0, 1, 2 for one index, then the other, not 0, 0, 1, 1, 2, 2?

I'm not sure what you are asking for. this? Please give an example of what you would the output to look like if not.
output.innerHTML += key + ' : ' + futures.ES[i][key] + '<br/>';

you've helped me out a lot, so even if you could just throw some terms at me to get me started I can go googling :google_lt:
I would just read through all the javascript tutorials and the AJAX tutorials and make sure you are comfortable with their contents that you could easily reproduce the examples they have. Whenever you have questions on, hit us up.
Link to comment
Share on other sites

thanks again, you're a great teacher, just like justsomeguy. I've checked in here for...years off and on with different experiments...now I want to learn what's under the hood with DOM, without relying on YUI, Jquery etc. this is listing the way I want, but is there a cleaner way, and how to get a space/break between the 2 for sections?document.write(" "); isn't working:

 for(var i = 0, l = futures.ES.length; i < l; i++){		 for(var key in futures.ES[i]){     output.innerHTML += futures.ES[i][key] + '<br/>';        };    }; //space here  for(var i = 0, l = futures.CL.length; i < l; i++){		 for(var key in futures.CL[i]){     output.innerHTML += futures.CL[i][key] + '<br/>';        };    };

Link to comment
Share on other sites

you're already adding breaks in your loops. just do it again

//loop 1output.innerHTML += '<br>';//loop 2

some would argue that you should do it with CSS, by using padding, and I would agree. I think you intended on making a list out of these, so I would apply CSS to the lists instead when you get to that point.

Link to comment
Share on other sites

thanks I'll work on css padding around lists. next task is to alert responseText from external website. just starting with that, as you suggest keep it simple. Firebug DOM onreadystatechange shows get readystate = 4 and get status =0 which seems to be a problem. when I use the window.onload function I'm not getting any onreadystatechange info, but do get nsxpccompents_interface info which I haven't seen before in firebug (?) anyhow here is the code; if you could please give me a pointer as how to proceed much appreciated.

//var output = document.getElementById('output'); var oXHR = new XMLHttpRequest();oXHR.open("GET", "http://www.ndbc.noaa.gov/station_page.php?station=casm1/", true);oXHR.onreadystatechange = function (oEvent) {  if (oXHR.readyState === 4) {	if (oXHR.status === 200) {	  console.log(oXHR.responseText)	} else {	  console.log("Error", oXHR.statusText);	}  }};oXHR.send(null);if(oXHR.status === 200){		console.log(oXHR.responseText);		//json = JSON.parse(oXHR.responseText);  }; alert(oXHR.responseText); 

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...