Read JSON String Shown In URL Using Javascript - javascript

i am trying to create a simple web app that gets the latitude and longitude stored in a JSON string and uses them to place markers on a google map. Currently, I have a program on a server which retrieves a JSON string with data when a URL is entered into a web browser. The JSON string produced is as follows:-
{"employees":[{"email":"bones93#hotmail.co.uk","lat":"53","lon":"-3","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"}]}
What method could i use in JavaScript that would allow me to get the JSON string that is produced?
P.S I know I will need to parse the text afterwards to make a JSON Object, this is something that can be done afterwards.

Use the Jquery library's get method to request the data from the server. Here is a link to a simple W3 tutorial : http://www.w3schools.com/jquery/ajax_get.asp
Your code will look something like this:
$("button").click(function(){
$.get("/your/server/url",function(data){
var result = JSON.parse(data);
// Process result.employees
});
});

You could use
var x = JSON.parse('{"employees":[{"email":"bones93#hotmail.co.uk","lat":"53","lon":"-3","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"},{"email":"unknown","lat":"0","lon":"0","alt":"0","date":"unknown","time":"unknown"}]}');
and then access it with:
x["employees"][0]["lat"];

try this for normal strings:
JSON.parse(str)
or if you're using AJAX to get that Json you can use as following:
$.get(..,'json')
OR
$.post(..,'json')

Related

My code wont print my object

When I try to print my object it gives me no response.
var steaminv = JSON.parse("http://steamcommunity.com/id/pootel/inventory/json/730/2.json");
document.write(steaminv);
You should request the file first and then parse the content of the file.
JSON.parse requires a json object encoded as string. It does not request the file for you.
If you are using node, you can use request module. If you are using javascript on browser, you can use jQuery and do an ajax call to get the content of the file.
Please take a look at this question: How do I receive a JSON file using AJAX and parse it using javascript?
Just to give you an idea what JSON.parse does:
var str = '{"name":"Amir","age":25}';
var obj = JSON.parse(str);
console.log(obj.name);
console.log(obj.age);

Print data from json file

I have json file with given data (total.json)
var data = {"trololo":{"info":"61511","path".... }}
I need to get object "info" and then print data "61511" in alert window
I include my json like
var FILE = 'total'
var data_file_names = {};
data_file_names[FILE] = 'total.json';
And then i use it like
var data_trololo = data_file_names[FILE];
Plese, help me print object "info". Maybe there is another way to solve this problem
You need to make an ajax call to the json file. Then you can access the array like the below example.
Note : Your json wasn't properly formatted.
var data = {
"trololo":{
"info": ["61511","path"]
}
};
console.log(data.trololo.info[0]); //this one will print 61511
Usually one can make an ajax call to read the file on the server.
But if you are ok with using HTML5 features then go through the link find out how to read the file on the browser itself. Though File API being part of HTML5 spec is stable across browsers.
http://www.html5rocks.com/en/tutorials/file/dndfiles/

Using jQuery to parse a JSONP where source uses a variable instead of a function

I am trying to parse some data from a source that is formatted like this:
var = jsonReturnData = {}
instead of this:
jsonReturnData({})
If I read the file using a script tag like this:
<script src="http://foundationphp.com/phpclinic/podata.php?startDate=20150301&endDate=20150302&raw"></script>
I have no problem reading the data, but if I try to do any sort of JSON or JSONP call from within jQuery, I either get an error or no access to the data depending on how I do it.
$.getJSON('http://foundationphp.com/phpclinic/podata.php?startDate=20150301&endDate=20150321&raw', function(data) {
console.log(jsonReturnData);
});
I need to be able to load the data dynamically when someone chooses some dates. Here's a sample of the interface working, but with no access to the JSON file. The data that you see is being read by the script method.
http://iviewsource.com/exercises/codeclinic/01/

JSON in Google Apps Script

I am trying to validate a webhook with Podio (https://developers.podio.com/doc/hooks/validate-hook-verificated-215241) using google apps script.
Currently I have the following script successfully writing data to a document (after the Podio Post is activated):
function doPost(l) {
var doc = DocumentApp.openById('1to3-JzhE27-LK0Zw7hEsdYgiSd7xQq7jjp13m6YwRh0');
var jstring = Utilities.jsonStringify(l);
doc.appendParagraph(jstring);
}
With the data appearing as follows:
{"queryString":null,"parameter":{"hook_id":"38035","code":"a92e06a2","type":"hook.verify"},"contextPath":"","parameters":{"hook_id":["38035"],"code":["a92e06a2"],"type":["hook.verify"]},"contentLength":44}
For some reason, google apps script won't let me take this data and access the properties like this:
jstring.parameter.code;
If I copy the (seemingly) JSON string into a separate script under a new variable, I can then access the data within the JSON.
What am I doing wrong here?
It looks like you have a JavaScript object that you convert to a JSON string, jstring. It is just a string. If you want to access the properties represented in the string, use the original object, l. Ie, l.parameter.code
function doPost(l) {
var doc = DocumentApp.openById('1to3-JzhE27-LK0Zw7hEsdYgiSd7xQq7jjp13m6YwRh0');
var jstring = Utilities.jsonStringify(l);
doc.appendParagraph(jstring);
dosomething(l.parameter.code);
}

Incorrect JSON data format

I am trying to create some JSON to be used for displaying a chart using Highcharts
http://www.highcharts.com/
I have copied one of their examples:
http://www.highcharts.com/stock/demo/basic-line
Click "View Options" under the graph to see the source. There is also a JSFiddle there to play with
If I copy that locally it all works fine.
The problem is when I try to use my own data source.
I have an ASP.Net MVC controler which is spitting out a list of arrays, just like their data source. However, that doesn't work.
Their datasource looks like this
http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?
and they retrieve it like this
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?', function (data) {
So I thought I'd take a step back and copy thier data exactly and put it in a text file on my server and try that:
So I tried this
$.getJSON('/data.txt', function (data) {
and this
$.get('/data.txt', function (data) {
but neither work
I have also tried using both JSON.parse and jQuery.parseJSON after retrieving the data, but again - that doesn't seem to work
I am also wondering what the ? is at the start of their data
Their data looks like this
?([[<some data>],[some data]]);
I don't get any error message, the graph just doesn't display
any ideas?
SOLVED IT
Just need to retrive the data and turn it into an array and pass it to the chart.
Needs to be an array, not JSON
That datasource is ouputting JSONP, which is for cross-domain AJAX requests. It's not valid 'raw' JSON because of that extra callback(...) wrapper.
Read up about it here: http://api.jquery.com/jQuery.ajax/ under the 'dataType' section.
As you say in your tags, it's not JSON, it's JSONP. Do not parse it, catch it with a callback. Use jQuery.getScript to do it, and define function callback(data). Inside that function, data should contain the (parsed) object. Also, replace the ? in the URL with callback (or whatever you named your function) - ? is not a valid identifier in JavaScript, so ?([....]) is nonsense.

Categories