Recalling data from a JSON array in Javascript error - javascript

I managed to get the JSON array into (look http://yrs2013.bugs3.com/mpapp/getSTORY.php?url=http%3A%2F%2Fcontent.guardianapis.com%2Fsearch%3Fq%3DJohn%20Stevenson%20mp%26page-size%3D3%26format%3Djson there for the array details), Javascript as a JS object - however now when i try and call a piece of data from the array it comes back as 'undefined'.. Any tips? :)
JS Code:
$.getJSON('getSTORY.php?url='+ url2, function(response)
console.log(response);
//logs the response, comes up as object in the log;
var e = response.status;
//when e is logged it just says 'undefined'
console.log(e);
In the log the object looks like drop down menus, which is different to my previous attempts of similar things as they came back from the PHP as text. I have tried JSON.parse but however that came back with the undefined o error! :l any help gratefully accepted! Thanks!

By looking at your JSON structure, I believe you need response.response.status. The first response is a variable holding your whole object, which contains a single response property with status inside (as well as results, etc).

Related

AWS Lambda: How do I get property inside event.body, it keep return undefined

I was trying to get event.body.data, but it keep return me undefined, i tried JSON.parse(event), JSON.parse(event.body), JSON.parse(event.body.data), JSON.stringify, almost tried out things that i can do with JSON and non of them seems to work. When i tried JSON.parse(event), will give syntax error. So i suspect it already in JSON object format and when i console.log it, it didn't have the " " quote. If it is already in JSON format, why can't I access the property in it. I also tried wrap it inside if(event.body.data) and it doesn't work as well. Anyone know how to get property inside event.body?
Based on your screenshot it looks like the body data is a JSON string. That means you have to parse it first before you can use it. Something like this:
exports.handler = function(event, context, callback) {
const body = JSON.parse(event.body)
console.log('data: ', body.data)
}
Then apply the suggestions from #Marcin and fix your JSON data because it's missing quotes.
Your even.body is invalid json string, which explain why JSON.parse fails. Thus, you should check who/what is making the request and modify the code of the client side to invoke your API with a valid json string.
It should be:
'{"action": "message, "data": "black clolor"}'
not
"{action: 'message, data: 'black clolor'}"
Thanks #Marcin for the feedback, it was indeed caused by invalid json string sent from frontend.
Changing it to the code below solved the issue.
{"action": "message", "data": "black clolor"}

Can't access JSON attributes

I've been battling with this seemingly simple issue for a good two hours now.. Please educate me. I just don't undestand what I'm doing wrong.
I have a PHP script that I call from a react component with a $.get function like so:
this.serverRequest = $.get("php/get_house.php", {"id":this.props.houseId}, function(data){
this.setState({house: data, loading: false});
}.bind(this));
I then pass the data in this.state.house into another component :
<ShowHouse house={this.state.house} />
In ShowHouse component I log the data:
console.log(this.props.house);
console.log(this.props.house[0]);
The first one returns something that chrome console shows as [{...}], with the data in 0:nth position, the second one returns what you'd expect - just the data in normal JSON format like in the block below.
My JSON that I get printed on the page if I simply open the PHP-script with an id, like ..php?id=1
[{"heading":"Kuin uusi","id":"1","city":"Helsinki"}]
How do I access this data? I get an error "Cannot read property 'heading' of undefined" if I simply try to access it by
console.log(this.props.house[0].heading).
You can use array syntax
this.props.house[0]["heading"]

Unable to load JSON (Javascript)

I'm trying to load a JSON file by link and then align data (like title, date etc) to variables so I can use them. Right now, I don't care about variables. I just want to alert() them but something seems like I'm doing it wrong, alert returns nothing!
I use JSfidle to run the code. The code is this:
var JSON_unparsed = $.getJSON('http://www.14deftera.gr/feeds/posts/default?orderby=published&alt=json') ;
var JSON = JSON.parse(JSON_unparsed) ;
alert(JSON.feed.entry[0].title.$t) ;
The URL I want to parse is: http://www.14deftera.gr/feeds/posts/default?orderby=published&alt=json
and here you can see the JSON how is structured if that can help you:
You can use JSONP for this:
Update, for better understanding how to work with returned JSON.
var id, title;
$.ajax({
url: 'http://www.14deftera.gr/feeds/posts/default?orderby=published&alt=json',
jsonp: "callback",
dataType: "jsonp"
}).done(function(r){
// r is returned JSON
for(var i in r)
// for ex ID is this
id = r[i].id.$t;
// and title
title = r[i].title.$t;
// and so on, check the json, I mean check the browser console by hitting F12, below code will print the whole JSON
console.log(r[i]);
});
Codepen link: http://codepen.io/m-dehghani/pen/grXrrp?editors=0010
In addition to adeneo's reply, in your code, JSON_unparsed variable is holding something called (differed or promise object), this object might be holding the data inside it,but you are using the wrong way to pull it out. in order for you to get it out, you need to call (.done()) function, see the below:
var JSON_unparsed = $.getJSON('http://www.14deftera.gr/feeds/posts/default?orderby=published&alt=json').done(function(json){
console.log(json);
console.log(json.feed.entry[0].title.$t);
});
aside from that, if you got an error with something like this:
XMLHttpRequest cannot load http://www.14deftera.gr/feeds/posts/default?orderby=published&alt=json&_=1459788714707. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://stackoverflow.com' is therefore not allowed access.
it means that you are not allowed to call this API/URL from your current domain.
One more thing, if you are using getJSON method, there is no need to parse the returned data, jquery will parse it for you

how can I access to a specific json value in my returned data

I send a http GET request which returns JSON data in the following form. I am finding it impossible to access this data despite having no problems with example json that I create. I want to ideally take the array under wifi, and use this data to create a html table, but I think I can work out how to create the table if I could just access the actual elements of the data.
I have tried multiple methods to try and reach the first timestamp. I have tried:
var element = result.undefined.clients.wifi[0].timestamp;
but this returns an error that 'clients' can't be found.
I also tried:
var element = result.clients.wifi[0].timestamp; //and
var element = result.wifi[0].timestamp;
The JSON data returned to a variable is shown below:
result = undefined
{"sourceId":"idid","sourceType":"CLOUD_source","searchMeta":{"maxResults":4,"metricType":["clients"],"family":["wifi"],"Interval":"M1"},
"clients":{"wifi":
[{"timestamp":1424716920,"avg":3,"min":1,"max":4,"Count":8,"sCount":3,"sources":["x1","x2","x3","x4","x5","x6","x7","x8"]},{"timestamp":1424716980,"avg":2,"min":1,"max":3,"Count":4,"sCount":2,"sources":["x3","x4","x8","x4"]},{"timestamp":1424717160,"avg":2,"min":1,"max":3,"Count":9,"sCount":4,"sources":["x3","x4"]}]}}
The JSON data is invalid. If it is returned from a server, you need to go there and correct the data source, (if you have access to that).
Otherwise, perhaps notify the backend guy(s) about it.
If it is from a REST API, and you are "sure" that the server code should be error free, then check that you have supplied all the required parameters in the API request you are making.
I think your JSON is messed up. I ran it through JSONLint, and having the undefined at the beginning causes things to break.

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