Access JSON data in UI5 - json

I'm trying to access the JSON data from the below URL:
http://api.openweathermap.org/data/2.5/weather?q=London
And get the below as response:
{
"coord": {
"lon": 174.77,
"lat": -36.87
},
"sys": {
"type": 1,
"id": 8276,
"message": 0.0568,
"country": "GB",
"sunrise": 1407093366,
"sunset": 1407130678
},
"weather": [
{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "10d"
}
],
"base": "cmc stations",
"main": {
"temp": 287.15,
"pressure": 1017,
"humidity": 76,
"temp_min": 287.15,
"temp_max": 287.15
},
"wind": {
"speed": 3.6,
"deg": 210
},
"clouds": {
"all": 76
},
"rain": {
"3h": 1
},
"dt": 1407115800,
"id": 2193733,
"name": "London",
"cod": 200
}
Kindly can you please suggest how do I access it in UI5?
I've done the following in order to set the model:
var jsonModel = new sap.ui.model.json.JSONModel();
jsonModel.loadData('http://api.openweathermap.org/data/2.5/weather?q=Auckland');
sap.ui.getCore().setModel(jsonModel);
I can see the response coming well in Chrome. How do I bind it to ui5 control? I've seen the binding syntax but gets either null or undefined error.
Please suggest.
Awaiting response.
Cheers,
AW

Just sap.ui.getCore().getModel(<your Modelname>).getData()
It's better to avoid the global model. You could use the view instead. Like: this.getView().setModel(new JSONModel(), "yourModel"). The model is bind to the view, so the controls within the view can access the model data.

Related

Problem getting data from json through http with riverpod

I have this json:
{
"coord": {
"lon": -3.7026,
"lat": 40.4165
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01n"
}
],
"base": "stations",
"main": {
"temp": 297.84,
"feels_like": 297.62,
"temp_min": 294.82,
"temp_max": 299.94,
"pressure": 1017,
"humidity": 48
},
"visibility": 10000,
"wind": {
"speed": 1.34,
"deg": 270,
"gust": 2.68
},
"clouds": {
"all": 0
},
"dt": 1631051279,
"sys": {
"type": 2,
"id": 2007545,
"country": "ES",
"sunrise": 1630993686,
"sunset": 1631039875
},
"timezone": 7200,
"id": 3117735,
"name": "Madrid",
"cod": 200
}
with this link:
http://api.openweathermap.org/data/2.5/weather?id=3117735&appid=899fc742471c1a7623a573d0bc7ad85b
I want to get the data, to make that I created the class with a json convert, and get want to get the data through a json.decode:
Future<Madrid> fetchMadrid() async {
final response = await http
.get(Uri.parse('http://api.openweathermap.org/data/2.5/weather?id=3117735&appid=899fc742471c1a7623a573d0bc7ad85b'))
.timeout(const Duration(seconds: 2));
if (response.statusCode == 200) {
return parseMadrid(response.body);
} else {
throw Exception('Error');
}
}
Madrid parseMadrid(String response) {
var list = json.decode(response);
Madrid photos = Madrid.fromJson(list);
return photos;
}
final madridStateProvider = FutureProvider<Madrid>((ref) async {
return fetchMadridLocal();
});
and get the data through a Future Provider with riverbed.
I get the error: Expected a value of type 'Coord', but got one of type '_JsonMap'

How do I access the name of the city nested in this api response?

I request data with axios.get(...), successful get the return as nested objects. I can access the data.message, data.cnt, data.cod but I can't access the properties of the "city". kept getting undefine or typeerror.
I want to access the properties of the city object nested within the response data. like this "data.city.name" but errors.
{
"cod": "200",
"message": 0.0051,
"cnt": 40,
"list": [
{
"dt": 1545318000,
"main": {
"temp": 282.74,
"temp_min": 282.167,
"temp_max": 282.74,
"pressure": 1012.86,
"sea_level": 1020.54,
"grnd_level": 1012.86,
"humidity": 84,
"temp_kf": 0.57
},
"weather": [
{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "10d"
}
],
"clouds": { "all": 44 },
"wind": { "speed": 5.67, "deg": 243.503 },
"rain": { "3h": 0.25 },
"sys": { "pod": "d" },
"dt_txt": "2018-12-20 15:00:00"
},
{
"dt": 1545739200,
"main": {
"temp": 282.628,
"temp_min": 282.628,
"temp_max": 282.628,
"pressure": 1037.58,
"sea_level": 1045.29,
"grnd_level": 1037.58,
"humidity": 100,
"temp_kf": 0
},
"weather": [
{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "10d"
}
],
"clouds": { "all": 76 },
"wind": { "speed": 2.02, "deg": 212.503 },
"rain": { "3h": 0.13 },
"sys": { "pod": "d" },
"dt_txt": "2018-12-25 12:00:00"
}
],
"city": {
"id": 2643743,
"name": "London",
"coord": { "lat": 51.5073, "lon": -0.1277 },
"country": "GB",
"population": 1000000
}
}
Use JSON.parse();
Example:
var data = JSON.parse(yourJSONObject)
console.log(data.city.name)
May not full represent what you need, but this should show how to set a default state, fetch your results, and then pass them into components. Your object is fine, I feel like you might be trying to access it before Axios completes.
export class DataView extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
data: {}
};
this.defaultState = {
// default properties of state
};
}
componentWillMount() {
this.fetchData();
}
fetchData = () => {
await axios.get( ${apiEndpoint}${inputCity}&appid=${apiKey} )
.then( data => {
this.setState({
data,
...this.defaultState,
isLoading: false
});
});
};
render() {
return (
<Fragment>
{this.state.isLoading ? ( // Check if it's still loading and load nothing if true
<Fragment />
) : (
<Component withProps={this.state.data}></Component> // Data can be accessed if isLoading: false
)}
</Fragment>
);
}
}
if you are getting data.message, then you must get the city name with data.city.name
I think you have some errors in your code because i can access the data and the json is also valid too.
try to console.log() the response and see what's going on.
Seems to work fine with data.city.name
const data = {
"cod": "200",
"message": 0.0051,
"cnt": 40,
"list": [
{
"dt": 1545318000,
"main": {
"temp": 282.74,
"temp_min": 282.167,
"temp_max": 282.74,
"pressure": 1012.86,
"sea_level": 1020.54,
"grnd_level": 1012.86,
"humidity": 84,
"temp_kf": 0.57
},
"weather": [
{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "10d"
}
],
"clouds": { "all": 44 },
"wind": { "speed": 5.67, "deg": 243.503 },
"rain": { "3h": 0.25 },
"sys": { "pod": "d" },
"dt_txt": "2018-12-20 15:00:00"
},
{
"dt": 1545739200,
"main": {
"temp": 282.628,
"temp_min": 282.628,
"temp_max": 282.628,
"pressure": 1037.58,
"sea_level": 1045.29,
"grnd_level": 1037.58,
"humidity": 100,
"temp_kf": 0
},
"weather": [
{
"id": 500,
"main": "Rain",
"description": "light rain",
"icon": "10d"
}
],
"clouds": { "all": 76 },
"wind": { "speed": 2.02, "deg": 212.503 },
"rain": { "3h": 0.13 },
"sys": { "pod": "d" },
"dt_txt": "2018-12-25 12:00:00"
}
],
"city": {
"id": 2643743,
"name": "London",
"coord": { "lat": 51.5073, "lon": -0.1277 },
"country": "GB",
"population": 1000000
}
}
document.write(data.city.name);
getData = async () => {
const { inputCity } = this.state;
try {
const data = await axios.get(${apiEndpoint}${inputCity}&appid=${apiKey});
this.setState({ data });
console.log(this.state.data);
return data;
} catch (err) {
console.error(err);
}
}

Weather graph using Angular 2, chart.js and json data

Using weather information that i receive from a service, i am trying to create a graph by means of chart.js.
I imported Chart into my project, and i am capable of using it using static data, but i am unable to use the data that i get from json.
What i am trying currently looks like this:
getForeCast()
{
this.weatherService.getForecastByCityName(this.searchString)
.subscribe(response =>
{
this.lineChartData = response.list.main.temp;
this.lineChartLabels = response.list.dt;
})
}
//LineChart
public lineChartData: Array<any>
public lineChartLabels: Array<any>
the getforecast() is activate in ngOnInit
the info that i receive from the json looks like this:
{
"cod": "200",
"message": 0.0054,
"cnt": 35,
"list": [
{
"dt": 1498748400,
"main": {
"temp": 21.87,
"temp_min": 21.25,
"temp_max": 21.87,
"pressure": 1006.93,
"sea_level": 1009.32,
"grnd_level": 1006.93,
"humidity": 62,
"temp_kf": 0.62
},
"weather": [
{
"id": 803,
"main": "Clouds",
"description": "broken clouds",
"icon": "04d"
}
],
"clouds": {
"all": 56
},
"wind": {
"speed": 6.81,
"deg": 227.001
},
"rain": {},
"sys": {
"pod": "d"
},
"dt_txt": "2017-06-29 15:00:00"
},
if i use the info to show it in a table, it works, but i can not get it to work in the graph.
Look at the update() method of the chart. Maybe you need to trigger it after you update your data in order for the chart to re-render.

Node-RED not able to access to array member

I'm trying to access to a JSON array returned by a OpenWeatherMap request.
The JSON data is:
{ "city":
{ "id": 3171457, "name": "New York", "coord": { "lon": 0.32898, "lat": 4.802662 }, "country": "US", "population": 0, "sys": { "population": 0 } },
"cod": "200", "message": 0.0317, "cnt": 40,
"list": [ { "dt": 1483552800, "main": { "temp": 277.28, "temp_min": 275.705, "temp_max": 277.28, "pressure": 1013.85, "sea_level": 1021.42, "grnd_level": 1013.85, "humidity": 93, "temp_kf": 1.57 }, "weather": [ { "id": 800, "main": "Clear", "description": "clear sky", "icon": "01n" } ], "clouds": { "all": 0 }, "wind": { "speed": 4.74, "deg": 269.002 }, "sys": { "pod": "n" }, "dt_txt": "2017-01-04 18:00:00" },
...
If i use in a template {{payload.list}} I see a list of [object Object]s.
But if I use {{payload.list[0]}}, or {{payload.list[0].main}}, I see nothing - my guess was a single [object Object].
How can i access to the first member and inner members?
The template node uses the mustache format, documented here: https://mustache.github.io/mustache.5.html
To access array values, you should use the following syntax:
{{ payload.list.0 }}
and
{{ payload.list.0.main }}

How to extract JSON parameter using JsonSlurper in Groovy

I've written the following groovy script in SOAPUI to execute an assertion on a JSON response.
I'm having difficulty writing the assertion to extract and assert on Weather > main > Clouds property and value of the JSON response.
Can someone please assist with correcting my code to extract the value I want?
Thanks!
import groovy.json.JsonSlurper
def json = '''{
"coord": {
"lon": -0.13,
"lat": 51.51
},
"weather": [
{
"id": 801,
"main": "Clouds",
"description": "few clouds",
"icon": "02n"
}
],
"base": "stations",
"main": {
"temp": 281.644,
"pressure": 1027.43,
"humidity": 100,
"temp_min": 281.644,
"temp_max": 281.644,
"sea_level": 1035.14,
"grnd_level": 1027.43
},
"wind": {
"speed": 3.33,
"deg": 43.5005
},
"clouds": {
"all": 12
},
"dt": 1476231232,
"sys": {
"message": 0.0084,
"country": "GB",
"sunrise": 1476253200,
"sunset": 1476292372
},
"id": 2643743,
"name": "London",
"cod": 200
}'''
def result = new JsonSlurper().parseText(json)
log.info(result)
assert result.weather.main == "Clouds"
Weather is an array of maps, as I see. So, you need to select an item or groovy will return to you an array of main.
assert result.weather.first().main == "Clouds"
​assert result.weather.main == ["Clouds"​]​
weather in your json is array. You can access it elements as a regular array
assert result.weather.main[0] == "Clouds"
assert result?.weather?.main?.getAt(0) == "Clouds"
second prefered because it null safe
Looks it's a trivial issue.
weather is an array(in []) and that is why the assertion fails.
"weather": [
{
"id": 801,
"main": "Clouds",
"description": "few clouds",
"icon": "02n"
}
],
If you do result.weather​.main​, then it returns a list which contains an element Clouds. But,not a single value as you expected.
So, you can do:
assert result.weather​[0].main == 'Clouds', 'Not matching the expected result' or
assert result.weather​.main == ['Clouds'] or
assert result.weather.main.contains('Clouds')
For suppose if weather is below (example with more elements in json array):
"weather": [
{
"id": 801,
"main": "Clouds",
"description": "few clouds",
"icon": "02n"
},
{
"id": 802,
"main": "CloudApps",
"description": "few clouds",
"icon": "03n"
}
],
Then assertion can be done
assert result.weather.main == ['Clouds', 'CloudApps']