Evaluate JSON using Rhino 1.6R7? - javascript

I'm using Rhino (https://github.com/mozilla/rhino) 1.67R via Apache Camel and am trying to evaluate the following JSON:
{
"coord": {
"lon": -4.75,
"lat": 54.08
},
"weather": [
{
"id": 801,
"main": "Clouds",
"description": "few clouds",
"icon": "02d"
}
],
"base": "stations",
"main": {
"temp": 17,
"pressure": 1024,
"humidity": 77,
"temp_min": 17,
"temp_max": 17
},
"visibility": 10000,
"wind": {
"speed": 4.6,
"deg": 80
},
"clouds": {
"all": 20
},
"dt": 1435922400,
"sys": {
"type": 1,
"id": 5103,
"message": 0.0888,
"country": "IM",
"sunrise": 1435895550,
"sunset": 1435956814
},
"id": 3042196,
"name": "Port Erin",
"cod": 200
}
The call to exchange.getIn().getBody() below returns the JSON above (I know this because request.setBody(exchange.getIn().getBody()) sets the body of the response to the JSON above):
var resp = eval (exchange.getIn().getBody());
var temp = resp['name'];
So, all I'm trying to do here is evalute the JSON, and grab a value ('name') from it. However, it is failing with the following error:
var temp = resp['name'];
request.setBody(temp);. Cause: org.mozilla.javascript.EvaluatorException: Java class "[B" has no public instance field or method named "name". (<Unknown Source>#2)
org.apache.camel.builder.script.ScriptEvaluationException: Failed to evaluate: js: var resp = eval (exchange.getIn().getBody());
var temp = resp['name'];
request.setBody(temp);. Cause: org.mozilla.javascript.EvaluatorException: Java class "[B" has no public instance field or method named "name". (<Unknown Source>#2)
at org.apache.camel.builder.script.ScriptBuilder.createScriptEvaluationException(ScriptBuilder.java:420)[270:org.apache.camel.camel-script:2.10.0.redhat-60065]
at org.apache.camel.builder.script.ScriptBuilder.evaluateScript(ScriptBuilder.java:347)[270:org.apache.camel.camel-script:2.10.0.redhat-60065]
at org.apache.camel.builder.script.ScriptBuilder.evaluate(ScriptBuilder.java:91)[270:org.apache.camel.camel-script:2.10.0.redhat-60065]
at org.apache.camel.builder.script.ScriptBuilder.evaluate(ScriptBuilder.java:95)[270:org.apache.camel.camel-script:2.10.0.redhat-60065]
at org.apache.camel.builder.ProcessorBuilder$4.process(ProcessorBuilder.java:96)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.util.AsyncProcessorConverterHelper$ProcessorToAsyncProcessorBridge.process(AsyncProcessorConverterHelper.java:61)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.processor.DelegateAsyncProcessor.processNext(DelegateAsyncProcessor.java:99)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.management.InstrumentationProcessor.process(InstrumentationProcessor.java:73)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.processor.DelegateAsyncProcessor.processNext(DelegateAsyncProcessor.java:99)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.processor.interceptor.TraceInterceptor.process(TraceInterceptor.java:91)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.processor.DelegateAsyncProcessor.processNext(DelegateAsyncProcessor.java:99)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.fabric.FabricTraceProcessor.process(FabricTraceProcessor.java:81)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.processor.DelegateAsyncProcessor.processNext(DelegateAsyncProcessor.java:99)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.processor.RedeliveryErrorHandler.processErrorHandler(RedeliveryErrorHandler.java:334)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.processor.RedeliveryErrorHandler.process(RedeliveryErrorHandler.java:220)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.processor.interceptor.StreamCachingInterceptor.process(StreamCachingInterceptor.java:52)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.processor.RouteContextProcessor.processNext(RouteContextProcessor.java:46)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.processor.DelegateAsyncProcessor.process(DelegateAsyncProcessor.java:90)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.processor.interceptor.DefaultChannel.process(DefaultChannel.java:308)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.util.AsyncProcessorHelper.process(AsyncProcessorHelper.java:73)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.processor.Pipeline.process(Pipeline.java:117)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.processor.Pipeline.access$100(Pipeline.java:43)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.processor.Pipeline$1.done(Pipeline.java:135)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.impl.MDCUnitOfWork$MDCCallback.done(MDCUnitOfWork.java:236)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.processor.RouteContextProcessor$1.done(RouteContextProcessor.java:56)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.processor.RedeliveryErrorHandler$1.done(RedeliveryErrorHandler.java:346)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.impl.MDCUnitOfWork$MDCCallback.done(MDCUnitOfWork.java:236)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.impl.MDCUnitOfWork$MDCCallback.done(MDCUnitOfWork.java:236)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.impl.MDCUnitOfWork$MDCCallback.done(MDCUnitOfWork.java:236)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.impl.MDCUnitOfWork$MDCCallback.done(MDCUnitOfWork.java:236)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.management.InstrumentationProcessor$1.done(InstrumentationProcessor.java:82)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.impl.MDCUnitOfWork$MDCCallback.done(MDCUnitOfWork.java:236)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.impl.ProducerCache$1.done(ProducerCache.java:321)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.processor.SendProcessor$2$1.done(SendProcessor.java:127)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.impl.MDCUnitOfWork$MDCCallback.done(MDCUnitOfWork.java:236)[272:org.apache.camel.camel-core:2.10.0.redhat-60077]
at org.apache.camel.component.jetty.JettyContentExchange.doTaskCompleted(JettyContentExchange.java:207)[368:org.apache.camel.camel-jetty:2.10.0.redhat-60065]
at org.apache.camel.component.jetty.JettyContentExchange.onResponseComplete(JettyContentExchange.java:108)[368:org.apache.camel.camel-jetty:2.10.0.redhat-60065]
at org.eclipse.jetty.client.HttpExchange$Listener.onResponseComplete(HttpExchange.java:1158)[100:org.eclipse.jetty.client:7.6.7.v20120910]
at org.eclipse.jetty.client.HttpExchange.setStatus(HttpExchange.java:305)[100:org.eclipse.jetty.client:7.6.7.v20120910]
at org.eclipse.jetty.client.AbstractHttpConnection$Handler.messageComplete(AbstractHttpConnection.java:337)[100:org.eclipse.jetty.client:7.6.7.v20120910]
at org.eclipse.jetty.http.HttpParser.parseNext(HttpParser.java:895)[96:org.eclipse.jetty.http:7.6.7.v20120910]
at org.eclipse.jetty.http.HttpParser.parseAvailable(HttpParser.java:240)[96:org.eclipse.jetty.http:7.6.7.v20120910]
at org.eclipse.jetty.client.AsyncHttpConnection.handle(AsyncHttpConnection.java:133)[100:org.eclipse.jetty.client:7.6.7.v20120910]
at org.eclipse.jetty.io.nio.SelectChannelEndPoint.handle(SelectChannelEndPoint.java:627)[98:org.eclipse.jetty.io:7.6.7.v20120910]
at org.eclipse.jetty.io.nio.SelectChannelEndPoint$1.run(SelectChannelEndPoint.java:51)[98:org.eclipse.jetty.io:7.6.7.v20120910]
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:608)[107:org.eclipse.jetty.util:7.6.7.v20120910]
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:543)[107:org.eclipse.jetty.util:7.6.7.v20120910]
at java.lang.Thread.run(Thread.java:745)[:1.7.0_72]
Caused by: org.mozilla.javascript.EvaluatorException: Java class "[B" has no public instance field or method named "name". (<Unknown Source>#2)
at org.mozilla.javascript.DefaultErrorReporter.runtimeError(DefaultErrorReporter.java:109)[407:org.apache.servicemix.bundles.rhino:1.0.0.7R2_3]
at org.mozilla.javascript.Context.reportRuntimeError(Context.java:938)[407:org.apache.servicemix.bundles.rhino:1.0.0.7R2_3]
at org.mozilla.javascript.Context.reportRuntimeError(Context.java:994)[407:org.apache.servicemix.bundles.rhino:1.0.0.7R2_3]
at org.mozilla.javascript.Context.reportRuntimeError2(Context.java:964)[407:org.apache.servicemix.bundles.rhino:1.0.0.7R2_3]
at org.mozilla.javascript.NativeJavaArray.get(NativeJavaArray.java:103)[407:org.apache.servicemix.bundles.rhino:1.0.0.7R2_3]
at org.mozilla.javascript.ScriptableObject.getProperty(ScriptableObject.java:1617)[407:org.apache.servicemix.bundles.rhino:1.0.0.7R2_3]
at org.mozilla.javascript.ScriptRuntime.getObjectElem(ScriptRuntime.java:1390)[407:org.apache.servicemix.bundles.rhino:1.0.0.7R2_3]
at org.mozilla.javascript.ScriptRuntime.getObjectElem(ScriptRuntime.java:1372)[407:org.apache.servicemix.bundles.rhino:1.0.0.7R2_3]
at org.mozilla.javascript.gen.c102._c0(<Unknown Source>:2)[mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.rhino/1.7R2_3:]
at org.mozilla.javascript.gen.c102.call(<Unknown Source>)[mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.rhino/1.7R2_3:]
at org.mozilla.javascript.ContextFactory.doTopCall(ContextFactory.java:398)[407:org.apache.servicemix.bundles.rhino:1.0.0.7R2_3]
at org.mozilla.javascript.ScriptRuntime.doTopCall(ScriptRuntime.java:3065)[407:org.apache.servicemix.bundles.rhino:1.0.0.7R2_3]
at org.mozilla.javascript.gen.c102.call(<Unknown Source>)[mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.rhino/1.7R2_3:]
at org.mozilla.javascript.gen.c102.exec(<Unknown Source>)[mvn:org.apache.servicemix.bundles/org.apache.servicemix.bundles.rhino/1.7R2_3:]
at com.google.code.scriptengines.js.javascript.RhinoCompiledScript.eval(RhinoCompiledScript.java:64)[268:scriptengines-javascript:1.1]
at javax.script.CompiledScript.eval(CompiledScript.java:30)[425:org.apache.servicemix.specs.scripting-api-1.0:2.0.0.redhat-60065]
at org.apache.camel.builder.script.ScriptBuilder.runScript(ScriptBuilder.java:357)[270:org.apache.camel.camel-script:2.10.0.redhat-60065]
at org.apache.camel.builder.script.ScriptBuilder.evaluateScript(ScriptBuilder.java:340)[270:org.apache.camel.camel-script:2.10.0.redhat-60065]
... 55 more
Any help is much appreciated.
Note:
I'm using eval here instead of JSON.parse as I believe JSON.parse is not implemented in Rhino 1.6R7. I get a 'JSON is not defined' error when trying to use JSON.parse
I cannot upgrade Rhino, I have to use 1.6R7

Related

Cannot access all property in a react component

I have a component with some call to the OpenWeatherMap API. I use useState and useEffect and I render a component displaying the data. I can access some property of the object I get in return of the API call but not all of them...
This is what I receive (openweathermap doc):
{"coord": { "lon": 139,"lat": 35},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01n"
}
],
"base": "stations",
"main": {
"temp": 281.52,
"feels_like": 278.99,
"temp_min": 280.15,
"temp_max": 283.71,
"pressure": 1016,
"humidity": 93
},
"wind": {
"speed": 0.47,
"deg": 107.538
},
"clouds": {
"all": 2
},
"dt": 1560350192,
"sys": {
"type": 3,
"id": 2019346,
"message": 0.0065,
"country": "JP",
"sunrise": 1560281377,
"sunset": 1560333478
},
"timezone": 32400,
"id": 1851632,
"name": "Shuzenji",
"cod": 200
}
I can access the id, the name, the timezone... But I cannot get the weather[0].icon I get an error Cannot read property '0' of undefined. I should be able to access either all properties or none. But only some of them, how come? Those data come from the same API call so I guess it has nothing to do with an "asyns" issue. Or could it ? I seem to struggle with this...
The [ means that weather is an array.
Try using weather[0].icon.

How can I get a specific data from an OpenWeatherMap API?

I am currently working on a website for my school assignment (Final Thesis for VWO which is the last year of middle school in the Netherlands) where I have a sidebar which is supposed to give me the current temperature thanks to the API that I got from OpenWeatherMap.
But after searching for a few hours I still have no clue how I'm supposed to do it.
I have just "learned" HTML and CSS within the last few days, so my knowledge with them is still at the bare minimum, and as I've understood it correctly I need JavaScript for this problem which I still do not completely understand either.
I currently have this code in my .html which I want to show the current temperature taken from the OpenWeatherMap API instead of the 6 degrees:
Outside Temp: 6&#8451
(Reason it's a link with no destination is because that looked better in the "sidebar" with bootstrap)
But I have no idea how I can change the 6℃ to the 276.01 kelvin which is the number I got from my API JSON website:
{"coord":{"lon":5.39,"lat":51.5},"weather":[{"id":804,"main":"Clouds","description":"overcast clouds","icon":"04n"}],"base":"stations","main":{"temp":276.01,"pressure":1008,"humidity":69,"temp_min":275.15,"temp_max":277.15},"visibility":10000,"wind":{"speed":5.1,"deg":70},"clouds":{"all":90},"dt":1542749460,"sys":{"type":1,"id":5208,"message":0.0034,"country":"NL","sunrise":1542697565,"sunset":1542728514},"id":2759040,"name":"Best","cod":200}
So I've been browsing and searching around the web and in w3schools and tried to get the data from the API by using the following script according to w3schools:
function loadDoc() {
var openweathermapapi = new XMLHttpRequest();
openweathermapapi.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var temperature = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = this.responseText;
}
};
openweathermapapi.open("GET", "http://api.openweathermap.org/data/2.5/weather?q=Best&APPID=9c0299218db10c8423221d49842d8488", true);
openweathermapapi.send();
}
After pressing a button that runs the loadDoc script I get the complete website, but I only want the "temp" part from the "main" variable and have no idea how to get it.
here's an example of getting current location's weather details
first get your current system's location using this
var getIP = 'http://ip-api.com/json/';
then, it returns you your location's details in json
THIS CODE GETS ENTIRE DATA ON LOCATION and sets it to your tag
var weatherjson = "";
var getIP = 'http://ip-api.com/json/';
var openWeatherMap = 'http://api.openweathermap.org/data/2.5/weather'
$.getJSON(getIP).done(function(location) {
$.getJSON(openWeatherMap, {
lat: location.lat,
lon: location.lon,
units: 'metric',
APPID: 'APIKEY'
}).done(function(weather) {
//set temperature from json to your <a> tag
$('#mytemp').text(weather.main.temp);
})
})
Explanation of above code:-
the sample json returned
{
"coord": {
"lon": -122.08,
"lat": 37.39
},
"weather": [
{
"id": 721,
"main": "Haze",
"description": "haze",
"icon": "50n"
},
{
"id": 711,
"main": "Smoke",
"description": "smoke",
"icon": "50n"
}
],
"base": "stations",
"main": {
"temp": 11.84,
"pressure": 1016,
"humidity": 81,
"temp_min": 10,
"temp_max": 13.3
},
"visibility": 11265,
"wind": {
"speed": 1.13,
"deg": 128.002
},
"clouds": {
"all": 90
},
"dt": 1542782400,
"sys": {
"type": 1,
"id": 471,
"message": 0.003,
"country": "US",
"sunrise": 1542812064,
"sunset": 1542848035
},
"id": 420006353,
"name": "Mountain View",
"cod": 200
}
The main column contains the degree of your own location named (TEMP)
"main": {
"temp": 11.84,
"pressure": 1016,
"humidity": 81,
"temp_min": 10,
"temp_max": 13.3
},
Now we need to show the TEMPERATURE on display level
Outside Temp: 6&#8451
given an identity to your temperature containing anchor tag named ID which is "mytemp"
now find the ID and update the temperature
//set temperature from json to your <a> tag
$('#mytemp').text(weather.main.temp);

Removing unwanted JSON data using JAVASCRIPT

I'm new to JSON and Javascript and had to make a table in Cloudant NoSQL.
So, I collected Weather data from a Weather Company in JSON format and sent it to Cloudant, but there was some data in JSON which wasn't relevant to the table I wanted to create.
Is there a way to remove the metadata and the column name "observation" from the JSON data I received using javascript?
JSON data I have:
{
"metadata": {
"language": "en-US",
"transaction_id": "1503766402801:1454518918",
"version": "1",
"latitude": 12.83,
"longitude": 77.68,
"expire_time_gmt": 1503771300,
"status_code": 200
},
"observation": {
"key": "43295",
"class": "observation",
"expire_time_gmt": 1503771300,
"obs_id": "43295",
"obs_name": "Bangalore",
"valid_time_gmt": 1503759600,
"day_ind": "N",
"temp": 75,
"wx_icon": 29
}
}
JSON data I want
{
"_id": "2e5e0da1f82157dd6f5d381a4c9ff84e",
"_rev": "1-b7a92ae5f96b051f0add3b26a14543c2",
"key": "43295",
"class": "observation",
"expire_time_gmt": 1503771300,
"obs_id": "43295",
"obs_name": "Bangalore",
"valid_time_gmt": 1503759600,
"day_ind": "N",
"temp": 75,
"wx_icon": 29
}
Thank you.
EDIT
I'm able to remove metadata using "delete data.metadata;", where data contains the JSON, but I still can't remove the "observation" word and the curly braces in the end.
Assuming your JSON is parsed, you can just assign all keys from all nested objects to a new object.
var myData = {
"metadata": {
"language": "en-US",
"transaction_id": "1503766402801:1454518918",
"version": "1",
"latitude": 12.83,
"longitude": 77.68,
"expire_time_gmt": 1503771300,
"status_code": 200
},
"observation": {
"key": "43295",
"class": "observation",
"expire_time_gmt": 1503771300,
"obs_id": "43295",
"obs_name": "Bangalore",
"valid_time_gmt": 1503759600,
"day_ind": "N",
"temp": 75,
"wx_icon": 29
}
}
myData = Object.keys(myData)
.reduce((res, key) => Object.assign(res, myData[key]), {});
console.log(myData);
There are some extra keys in your result. Not sure where those are coming from.
If there are some extra properties to delete, you can use delete to get rid of those.
["latitude", "longitude"].forEach(k => delete myData[k]);
Or perhaps I misunderstood. I though you wanted a consolidation. If you only wanted the observation object, then just assign it to the original variable.
myData = myData.observation;
And add whatever other properties you'd like.
You can create a new json object before sending. Using lodash should be an easy solution in extending
// Assume result has your json data
var wantedJson = _.extend({}, result.observation, result.metadata);
If you are not bothered about the order of the elements, this is the simplest way:
var result = {
"metadata": {
"language": "en-US",
"transaction_id": "1503766402801:1454518918",
"version": "1",
"latitude": 12.83,
"longitude": 77.68,
"expire_time_gmt": 1503771300,
"status_code": 200
},
"observation": {
"key": "43295",
"class": "observation",
"expire_time_gmt": 1503771300,
"obs_id": "43295",
"obs_name": "Bangalore",
"valid_time_gmt": 1503759600,
"day_ind": "N",
"temp": 75,
"wx_icon": 29
}
}
var myjson = result.observation;
myjson._id = "2e5e0da1f82157dd6f5d381a4c9ff84e",
myjson._rev = "1-b7a92ae5f96b051f0add3b26a14543c2";
console.log(myjson);

Ajax data object unexpected behavior

Im having hard time traversing this data set pulled from an ajax call to a weather api. I want to get the values of things such as the temp or id but keep getting errors. Ive tried this weather.weather['id'], weather.weather.id, weather.weather[0]. I know the top weather layer is an object. But the second weather is passing an array? That has an object? how do i pull the information from this? I have some idea of doing this for normal data sets but this is acting weird for me. NOTE THIS IS WITH VUEJS
AJAX CALL:
$.getJSON('http://api.openweathermap.org/data/2.5/weather?id=6356055&appid=44db6a862fba0b067b1930da0d769e98', function(weather) {
this.weather_data = weather;
}.bind(this));
This is wear i push the data to my empty array
weather_data: [],
then for now im just trying to make sure its working within some pretags like this:
{{ weather_data.weather[0].id | json}}
and here is what is pulled back from the getjson call.
"weather": {
"coord": {
"lon": 2.13,
"lat": 41.4
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01d"
}
],
"base": "cmc stations",
"main": {
"temp": 285.622,
"pressure": 1006.71,
"humidity": 98,
"temp_min": 285.622,
"temp_max": 285.622,
"sea_level": 1015.25,
"grnd_level": 1006.71
},
"wind": {
"speed": 2.61,
"deg": 267.501
},
"clouds": {
"all": 0
},
"dt": 1457178093,
"sys": {
"message": 0.0042,
"country": "ES",
"sunrise": 1457158704,
"sunset": 1457200063
},
"id": 6356055,
"name": "Barcelona",
"cod": 200
},
trying this weather_data.weather yeilds this
[
{
"id": 801,
"main": "Clouds",
"description": "few clouds",
"icon": "02d"
}
]
First of all, with this types of problems I'd recommend using console.log(your_variable) and looking in the browser's console (F12 in Chrome) what you really have. Otherwise, data.weather.weather[0].id should work, if your original api response is stored in the variable named "data".

TypeError when accessing JSON string

I'm using the http://blockchain.info/api/api_websocket websocket api.
My json object for each transaction looks like this:
{
"op": "utx",
"x": {
"hash": "f6c51463ea867ce58588fec2a77e9056046657b984fd28b1482912cdadd16374",
"ver": 1,
"vin_sz": 4,
"vout_sz": 2,
"lock_time": "Unavailable",
"size": 796,
"relayed_by": "209.15.238.250",
"tx_index": 3187820,
"time": 1331300839,
"inputs": [
{
"prev_out": {
"value": 10000000,
"type": 0,
"addr": "12JSirdrJnQ8QWUaGZGiBPBYD19LxSPXho"
}
}
],
"out": [
{
"value": 2800000000,
"type": 0,
"addr": "1FzzMfNt46cBeS41r6WHDH1iqxSyzmxChw"
}
]
}
}
I'm accessing the "addr" variable by using json.x.out[0].addr which prints out fine in a console.
However when I run a command through mongoose:
Game.findOne({address:json.x.out[0].addr},function (err, game) {
results in following error:
TypeError: Cannot read property 'x' of undefined
at Promise.<anonymous> (/Users/michael/Desktop/DugleyBit/app.js:176:25)
at Promise.addBack (/Users/michael/Desktop/DugleyBit/node_modules/mongoose/lib/promise.js:133:8)
at Promise.EventEmitter.emit (events.js:96:17)
at Promise.emit (/Users/michael/Desktop/DugleyBit/node_modules/mongoose/lib/promise.js:66:38)
at Promise.complete (/Users/michael/Desktop/DugleyBit/node_modules/mongoose/lib/promise.js:77:20)
at Query.findOne (/Users/michael/Desktop/DugleyBit/node_modules/mongoose/lib/query.js:1607:15)
at model.Document.init (/Users/michael/Desktop/DugleyBit/node_modules/mongoose/lib/document.js:227:11)
at model.init (/Users/michael/Desktop/DugleyBit/node_modules/mongoose/lib/model.js:196:36)
at Query.findOne (/Users/michael/Desktop/DugleyBit/node_modules/mongoose/lib/query.js:1605:12)
at exports.tick (/Users/michael/Desktop/DugleyBit/node_modules/mongoose/lib/utils.js:404:16)
Is it not a string? How can I convert it?
Thanks
Edit:
Please note that json is properly formated:
var json = JSON.parse(message);
Looks like json variable is not available in scope where you call Game.findOne.

Categories