Strange JSON response (" "=> ,) in rails app - javascript

I'm getting a json response from the forecast.io api with
JSON.parse(open("https://api.forecast.io/forecast/api-key/latitude,longitude").read)
And it looks like this
{"latitude"=>58.5942,
"longitude"=>16.1826,
"timezone"=>"Europe/Stockholm",
"offset"=>2,
"currently"=>{
"time"=>1367829429,
"summary"=>"Clear",
"icon"=>"clear-day",
"precipIntensity"=>0,
"temperature"=>59.04,
"dewPoint"=>41.6,
"windSpeed"=>11.49,
"windBearing"=>224,
"cloudCover"=>0.08,
"humidity"=>0.53,
"pressure"=>1022.88,
"visibility"=>6.21,
"ozone"=>319.4
}
I'm new to json but this is not regular json right? What should I do to get this to my view in script tags?
Thanks.

Use the particular JSON Keymap you want in the call, and return it in the JSON request callback function. I believe that would resolve your problem.

response = HTTParty.get('https://api.forecast.io/forecast/api-key/latitude,longitude', {:timeout => 3})
#currenttemp = response["temp"]
it will return in a json object because it detects it is JSON. (HTTParty is just a helper gem)

Related

Data coming from backend is stored in object but not accessible in object properties

Data coming from backend is stored in object but when i tries to print in using object properties its showing undefined. Here is my output:
enter image description here
my code:
this.documentService.getDocumentbyId(this.id).subscribe(
data => {
this.upmDoc=data;
console.log("UPM Data Fetched:",this.upmDoc);
console.log("Name:",this.upmDoc.name);
console.log("Symbolic Name:",this.upmDoc.symbolicName);
console.log("Object Store:",this.upmDoc.objectStore);
console.log("Active:",this.upmDoc.active);
},
error => console.log(error)
);
Its better to provide the response JSON instead of image to make sure where the problem is.
It looks like your service return HTTP Response not the body of the response. try to access the body of the data instead. replace the third line with:
this.upmDoc = data.body;
or
this.upmDoc = data["Document Details"];
based on your returned JSON.

Read JSON String Shown In URL Using 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')

Retrieve nested javascript objects in Django view as a dict

I have a very simple view that receives an ajax request containing a javascript object. The jquery request looks like this:
$.get(URL, {'kwargs': {test: 1}}, function(data){//whatever})
The problem is, request.GET now contains a rather strange key and looks like this:
{'kwargs[test]': [1]}
How can I successfully decode this? As a side note, it is impossible to know the key (test) beforehand
The expected format obtained is a python dict that looks like the one in the request.
I've tried:
request.GET.get('kwargs', None)
And I'd expect this as a result:
{'test': 1}
However, I get None, as the real key is 'kwargs[test]'
EDIT
I know I could use some kind of regex to accomplish this, but it feels as 'reinventing the wheel', as this use case is not that rare
I would recommend using JSON when communicating back and forth between the server and client for this type of situation. JSON is meant to handle these types of nested structures in a uniform manner.
Take a look at using the jQuery $.getJSON functionality,
http://api.jquery.com/jquery.getjson/
The following is an example of how this structure would look...
Javscript
var request_data = {kwargs: {test: 1}};
$.getJSON(URL, {data: JSON.stringify(request_data)}, function(data){//whatever})
Django
import json
def your_view(request):
my_json = json.loads(request.GET['data'])
Doing this will allow you to parse the request which contains JSON data into a variable of your choice (my_json). Once you assign your variable with the results of json.loads(), you will now have a python object containing the parsed requested JSON data and you will be able to manipulate your object accordingly.
>>> my_json['kwargs']
{u'test': 1}

JSON response from Google Analytics api

I am using the google-api-ruby-client to get a response from the Google Analytics api, which is successful, the one thing I am a little confused with though is the response object. I would like to know how to drill down into specific keys and their values or even parse the response to make it more understandable.
Below is what I believe is the relevant part of the JSON response
"{\"kind\":\"analytics#gaData\",\"id\":\"https://www.googleapis.com/analytics/v3/data/ga?ids=ga:88893966&dimensions=ga:pagePath&metrics=ga:pageviews&filters=ga:pagePath%3D%3D/&start-date=2014-01-01&end-date=2014-07-22\",\"query\":{\"start-date\":\"2014-01-01\",\"end-date\":\"2014-07-22\",\"ids\":\"ga:88893966\",\"dimensions\":\"ga:pagePath\",\"metrics\":[\"ga:pageviews\"],\"filters\":\"ga:pagePath==/\",\"start-index\":1,\"max-results\":1000},\"itemsPerPage\":1000,\"totalResults\":1,\"selfLink\":\"https://www.googleapis.com/analytics/v3/data/ga?ids=ga:88893966&dimensions=ga:pagePath&metrics=ga:pageviews&filters=ga:pagePath%3D%3D/&start-date=2014-01-01&end-date=2014-07-22\",\"profileInfo\":{\"profileId\":\"88893966\",\"accountId\":\"53082810\",\"webPropertyId\":\"UA-53082810-1\",\"internalWebPropertyId\":\"85713348\",\"profileName\":\"All Web Site Data\",\"tableId\":\"ga:88893966\"},\"containsSampledData\":false,\"columnHeaders\":[{\"name\":\"ga:pagePath\",\"columnType\":\"DIMENSION\",\"dataType\":\"STRING\"},{\"name\":\"ga:pageviews\",\"columnType\":\"METRIC\",\"dataType\":\"INTEGER\"}],\"totalsForAllResults\":{\"ga:pageviews\":\"8\"},\"rows\":[[\"/\",\"8\"]]}"
which is obtained from
# make queries
result = client.execute(:api_method => api_method, :parameters => {
'ids' => PROFILE,
'start-date' => Date.new(2014,1,1).to_s,
'end-date' => Date.today.to_s,
'dimensions' => 'ga:pagePath',
'metrics' => 'ga:pageviews',
'filters' => 'ga:pagePath==/'
})
puts ap(result)
Also when I do:
puts ap(result.data.rows.inspect)
#returns
"[[\"/\", \"8\"]]"
and when i try
response = JSON.parse(result.data.totalsForAllResults)
puts ap(response)
# returns error
TypeError: no implicit conversion of #<Class:0x00000001950550> into String
I am wondering how I can format the response without the backslashes and how I would say get the total page views?
Your syntax is off.
If result is simply a string that is a json object, which it looks like above, what you want is:
response = JSON.parse(result)
ap response["totalsForAllResults"]["ga:pageviews"]
Looking at the google-api-ruby-client the result.data returns an object if parseable from api schema, a hash if you pass the media type "application/json", or a string otherwise. So you need to determine if you are accessing the response data as an object or a Hash. My example above parses the raw string into a ruby hash.
tl;dr; there are multiple ways to attain the data you want.
Yes, your syntax is off. It should look something like this.
https://www.googleapis.com/analytics/v3/data/ga?ids=ga:_____&dimensions=ga:date&metrics=ga:impressions,ga:adClicks,ga:adCost&start-date=2015-10-13&end-date=today
BaseUrl, id, metrics, start-date and end-date are required. And don't forget to insert the access_token as well.

Problems with displaying JSON data I got from a server

I'm new to JSON/AJAX and
I've some problems with displaying data out of a JSON-object I've got from a server..
The url "http://localhost:8387/rest/resourcestatus.json" represents this object, which I would like to display via HTML/Javascript.. This object stores some monitoring information:
{"groupStatus":[
{"id":"AL Process","time":1332755316976,"level":0,"warningIds":[],"errorIds":[]},
{"id":"AL:instance1","time":1332919465317,"level":0,"warningIds":[],"errorIds":[]},
{"id":"AL:instance2","time":1332919465317,"level":1,"warningIds":["documentarea.locked"],"errorIds":[]},
{"id":"SL","time":1331208543687,"level":0,"warningIds":[],"errorIds":[]}
]}
Since the requested url is different from my domain I can't create a typical XMLHttpRequest.. So I found out that there's an AJAX cross-domain request which can be realised via jQuerys "getJSON()" method.
I want to display the ids and their level in a table.
Any solution to achieve this?
i think you are referring to JSONP. see jQuery.ajax Ex:
var url = 'http://localhost:8387/rest/resourcestatus.json';
$.getJSON(url+'?callback=?', function(data)
{
//data is
/*{
"groupStatus":
[
{"id":"AL Process","time":1332755316976,"level":0,"warningIds":[],"errorIds":[]},
{"id":"AL:instance1","time":1332919465317,"level":0,"warningIds":[],"errorIds":[]},
{"id":"AL:instance2","time":1332919465317,"level":1,"warningIds":["documentarea.locked"],"errorIds":[]},
{"id":"SL","time":1331208543687,"level":0,"warningIds":[],"errorIds":[]}
]
}*/
});
on the server side you will need to wrap the response into a JavaScript function: response = Request["callback"] +"("+ response+")";
the result will look like this:
?({"groupStatus":[{"id":"AL ....})
So the browser will actually load a valid java script code.
The callback function of $.getJSON contains the result of the AJAX call in it's argument.
$.getJSON('http://localhost:8387/rest/resourcestatus.json', function(data) {
$(data.groupStatus).each(function() {
// do something with $(this).id
});
});

Categories