Javascript parse json from URL - javascript

Trying to parse a json response from URL in javascript.
Here is what the response looks like
{"data":[{"version":"7.4.0","startDate":"2016-12- 12","totalSessions":"6208723","totalCrashes":"2944","crashRate":"0.047"},{"version":"7.4.0","startDate":"2016-12-11","totalSessions":"4979676","totalCrashes":"2378","crashRate":"0.048"},{"version":"7.4.0","startDate":"2016-12-10","totalSessions":"534913","totalCrashes":"208","crashRate":"0.039"},{"version":"7.4.0","startDate":"2016-12-09","totalSessions":"309564","totalCrashes":"147","crashRate":"0.047"},{"version":"7.4.0","startDate":"2016-12-08","totalSessions":"255597","totalCrashes":"162","crashRate":"0.063"},{"version":"7.4.0","startDate":"2016-12-07","totalSessions":"21379","totalCrashes":"12","crashRate":"0.056"}]}
I can dump the json output using
var crash = $.post('http://localhost/crash_stats.php', function(data2) {
$('#show-list').html(data2); //shows json
});
Then I tried to parse it using
document.getElementById("placeholder").innerHTML=data2.data[0].version
also tried
obj = JSON.parse(crash);
console.log(obj.data2[0].version);
But no luck.

You should tell jQuery that the AJAX function returns JSON, then it will parse it automatically for you.
var crash = $.post('http://localhost/crash_stats.php', function(data2) {
$("#placeholder").text(data2.data[0].version);
}, 'json');
Or you can call JSON.parse() yourself.
var crash = $.post('http://localhost/crash_stats.php', function(data2) {
var data = JSON.parse(data2);
$("#placeholder").text(data.data[0].version);
});

Related

Decoding payload with JavaScript

i need some support in parsing a payload with javascript. Below you see the json body. I need to return only the valuetype "occupants".
{"id":"8684bc99-5a69-4b7a-92c2-69faa91b668b","type":"airthings-webhook-cloudevent-occupancy-ventilation-sample-feed","source":"https://dashboard.airthings.com/integrations/webhooks/2c823594-3c4b-4352-9929-8486a5f8a985","dataContentType":"application/json","labels":{},"data":[{"measurementSystem":"METRIC","serialNumber":"2930118961","recorded":"2022-05-04T08:55:00","occupants":4.0,"ventilationAmount":171.0,"ventilationState":true,"ratings":{},"sensorUnits":{"occupants":"occ","ventilationAmount":"m3h","relativeVentilationRate":"ach"}}],"time":"2022-05-04T08:58:20.322709","specVersion":"0.2"}
I made it to return the "data" array with the following decoder. Now i need the object "occupants" within data. Can someone tell me what I need to adjust in the following code?
function Decoder(request) {
// Parse JSON into Object
var payload = JSON.parse(request.body);
// Load Data from JSON
var data = payload.data;
var Occupancy = data.occupants;
//var humidity = data.hum;
//var battery = data.bat;
// Forward Data into Device using Serial
return data;
}

Json Ajax Response from Django Application

I have a Django app that the views.py sends a json data to a javascript function on my html. The problem is that I can not access the elements of the data.
I tryied to use JsonParse but not sucess, for instance when I do
var other = JSON.parse(data_doc_pers['data_doc_pers']);
document.getElementById("text_conf4").innerHTML = other['doc_nome'];
I receive the following response: [object Object]
what I am doing wrong???
Here is my code
Views.py
...
json_string = json.dumps({'type_numeric':type_numeric,'type_prop':type_prop,'name':name,'Vinculo':Vinculo,'doc_nome':doc_nome})
return JsonResponse({'data_doc_pers':json_string})
HTML
$.get('{% url "page" %}',{'var':var}, function (data_doc_pers) {
var other = JSON.parse(data_doc_pers['data_doc_pers']);
document.getElementById("text_conf4").innerHTML = other['doc_nome'];
});
Problem solvend!
The error I was doing in javscript was to use var other = JSON.parse(data_doc_pers['data_doc_pers']); the correct should be only (data_doc_pers['data_doc_pers'].

Node.js and Express - Sending JSON object from SoundCloud API to the front-end makes it a string

I have been using an http.get() to make calls to the SounbdCloud API method to receive a JSON object that I would like to pass to the browser. I can confirm that the data I receive is an object, since I the typeof() method I call on the data prints out that it is an object.
var getTracks = http.get("http://api.soundcloud.com/tracks.json?q="+query+"&client_id=CLIENT_ID", function(tracks) {
tracks.on('data', function (chunk) {
console.log(typeof(chunk)); // where I determine that I receive an object
res.send(chunk);
});
//console.log(tracks.data);
}).on("error", function(e){
console.log("Got error: "+e);
});
But when I check the data I receive in the AJAX request I make in the browser, I find that the data received has a type of String (again, I know this by calling typeof())
$('#search').click(function(e){
e.preventDefault();
var q = $("#query").val();
$.ajax({
url: '/search',
type: 'POST',
data: {
"query": q
},
success: function(data){
alert(typeof(data));
alert(data);
},
error: function(xhr, textStatus, err){
alert(err);
}
})
});
I would appreciate the help, since I do not know where the problem is, or whether I am looking for the answer in the wrong places (perhaps it has something to do with my usage of SoundCloud's HTTP API)
JSON is a string. I assume you need an Object representing your JSON string.
Simply use the following method.
var obj = JSON.parse(data);
Another example would be:
var jsonStr = '{"name":"joe","age":"22","isRobot":"false"}';
var jsonObj = JSON.parse(jsonStr);
jsonObj.name //joe
jsonObj.age // 22

Addon firefox php request

i'm trying to develop Firefox extension
problem :
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "file.php",
onComplete: function (response) {
var List = response.json;
}
});
I want to use this request function to parse json to an array (List here) from php file.
The php my php file echo json form correctly, but I can't transform the data into javascript array to be able to use it in my addon.
if there is a better idea than using this function to do it please tell me :)
try this: MDN - JSON Object
JSON.parse and JSON.stringify
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "file.php",
onComplete: function (response) {
var List = JSON.parse(response.json);
}
});
it's very important to use double quotes.
If you are having a problem with JSON.parse. Copy your array to scratchpad and then run JSON.stringify on it and then make sure your php file matches the strignified result.
if Addon-SDK doesnt have JSON then you gotta require the module if there is one. If there isn't one than require('chrome') and grab the component HERE
There's a bug in Noitidarts code.
why JSON.parse the request.json? If you want to parse do it on request.text
However no need to json.parse as the request module tries to parse and if successful retuns request.json
see here:
var Request = require("sdk/request").Request;
var latestTweetRequest = Request({
url: "https://api.twitter.com/1/statuses/user_timeline.json?screen_name=mozhacks&count=1",
onComplete: function (response) {
var tweet = response.json[0];
console.log("User: " + tweet.user.screen_name);
console.log("Tweet: " + tweet.text);
}
});
// Be a good consumer and check for rate limiting before doing more.
Request({
url: "http://api.twitter.com/1/account/rate_limit_status.json",
onComplete: function (response) {
if (response.json.remaining_hits) {
latestTweetRequest.get();
} else {
console.log("You have been rate limited!");
}
}
}).get();
so the likely problem is that your php is not outputting a json string that json.parse can read. make sure to use ". figure out what your php file should return by running json.stringify on a dummy object. ie:
var obj = {myarr:[1,8,9,7,89,0,'ji'],strr:'khhkjh',anothrtObj:{1:45,56:8}};
alert(JSON.stringify(obj)) //{"myarr":[1,8,9,7,89,0,"ji"],"strr":"khhkjh","anothrtObj":{"1":45,"56":8}}
so now in your php make sure your outputted text mateches this format
{"myarr":[1,8,9,7,89,0,"ji"],"strr":"khhkjh","anothrtObj":{"1":45,"56":8}}
if your php outputs something like below JSON.parse will fail on it so request.json will be null
{myarr:[1,8,9,7,89,0,"ji"],strr:"khhkjh",anothrtObj:{"1":45,"56":8}}
or
{'myarr':[1,8,9,7,89,0,"ji"],'strr':"khhkjh",'anothrtObj':{"1":45,"56":8}}
or
{'myarr':[1,8,9,7,89,0,'ji'],'strr':'khhkjh','anothrtObj':{'1':45,'56':8}}

Parsing a data feed results in a Invalid Character error in WinJS

I am calling the Flickr data feed in WinJS for a Windows 8 Metro App. When I attempt to parse the feed response with JSON.parse, I get an Invalid Character error. Here is my code:
function processPhotos(result)
{
var photoData = JSON.parse(result.responseText);
//bind here
data.items.forEach(function (item) {
list.push(item);
});
}
function processError(error) {
console.log(error.message);
}
WinJS.xhr({ url: "http://api.flickr.com/services/feeds/photos_public.gne?format=json" }).then(processPhotos, processError);
WinJS.Namespace.define("data", {
items: groupedItems,
groups: groupedItems.groups,
getItemsFromGroup: getItemsFromGroup
});
Result.ResponseText has the expected content.
Does anyone else encounter this?
I had to do this to clear out some of the invalid characters in the responseText. (suggested to me by https://stackoverflow.com/users/200698/devhammer)
var cleansed = result.responseText.replace(/\\'/g, "'");
var photoData = JSON.parse(cleansed).d;
If you look at the data, you will notice it's not JSON, it's JSONP. That's the reason why JSON.parse() can't process it. If you want normal JSON, according to the documentation, you should use nojsoncallback=1:
http://api.flickr.com/services/feeds/photos_public.gne?format=json&nojsoncallback=1

Categories

Resources