How to join Json response element - arrays

I am making a call to the OpenWeatherApi am facing a dilemma. I am pulling the response, but only need specific data elements. I am successfully pulling certain elements, but am having trouble pulling the CITY element.
This is the response from the API call:
{
"coord": {
"lon": -122.4,
"lat": 45.64
},
"weather": [
{
"id": 800,
"main": "Clear",
"description": "clear sky",
"icon": "01n"
}
],
"base": "stations",
"main": {
"temp": 287.5,
"pressure": 1022,
"humidity": 82,
"temp_min": 284.25,
"temp_max": 289.25
},
"visibility": 16093,
"wind": {
"speed": 0.96,
"deg": 10.5029
},
"clouds": {
"all": 1
},
"dt": 1537854780,
"sys": {
"type": 1,
"id": 2321,
"message": 0.0172,
"country": "US",
"sunrise": 1537884050,
"sunset": 1537927234
},
"id": 420040945,
"name": "Vancouver",
"cod": 200
}
This is my mapping for the specific elements I need:
const main = response.data["main"]
const sys = response.data["sys"]
const city = response.data.name;
const weather = response.data["weather"][0]
const data = Object.assign(main, weather, sys, city)
res.send(data)
console.log(data)
Finally, this is the response from my mapping:
{
"0": "C",
"1": "i",
"2": "n",
"3": "c",
"4": "i",
"5": "n",
"6": "n",
"7": "a",
"8": "t",
"9": "i",
"temp": 293.74,
"pressure": 1018,
"humidity": 90,
"temp_min": 293.15,
"temp_max": 294.25,
"id": 2179,
"main": "Rain",
"description": "light rain",
"icon": "10n",
"type": 1,
"message": 0.0044,
"country": "US",
"sunrise": 1537874932,
"sunset": 1537918192
}
As you can see, CITY is split up into separate elements. If I only pull CITY, it pulls the accurate City just fine, as
"Cincinnati"
not
"name": "Cincinnati".
How can I join the elements for form the city, or recreate the "name": "City" element altogether?

you are getting wrong result because city is an array and its getting spread. change your code to below code
Object.assign({}, main, weather, sys, {city})
or
Object.assign({}, main, weather, sys, {name:city})
Solution is to convert array value to object property.

Related

How to get certain keys from the array of objects and put them in state?

I am training to do requests to server with json.placeholder. The result of request is the array of objects with many keys.
For example the array of objects
[
{
"id": 1,
"name": "Leanne Graham",
"username": "Bret",
"email": "Sincere#april.biz",
"address": {
"street": "Kulas Light",
"suite": "Apt. 556",
"city": "Gwenborough",
"zipcode": "92998-3874",
"geo": {
"lat": "-37.3159",
"lng": "81.1496"
}
},
"phone": "1-770-736-8031 x56442",
"website": "hildegard.org",
"company": {
"name": "Romaguera-Crona",
"catchPhrase": "Multi-layered client-server neural-net",
"bs": "harness real-time e-markets"
}
},
{
"id": 2,
"name": "Ervin Howell",
"username": "Antonette",
"email": "Shanna#melissa.tv",
"address": {
"street": "Victor Plains",
"suite": "Suite 879",
"city": "Wisokyburgh",
"zipcode": "90566-7771",
"geo": {
"lat": "-43.9509",
"lng": "-34.4618"
}
},
"phone": "010-692-6593 x09125",
"website": "anastasia.net",
"company": {
"name": "Deckow-Crist",
"catchPhrase": "Proactive didactic contingency",
"bs": "synergize scalable supply-chains"
}
},
and so on ...
But I don't need all these keys. Only to take some of them, for example name, username and id and put it in my State.
How to do that properly?
TL;DR
response = [ { "id": 1, "name": "Leanne Graham", ...}, {...}, ...]
cleanResponse = response.map(user => return {name: user.name, contact: user.email})
Here, with .map we return an object that has two property : name and contact.
We set name to user.name and contact to user.email
Anwser
I don't know much about ReactJS, but your anwser only require basic javascript :
Array.Map
You can use .map on an array to convert its elements :
nameArray= [ "George", "Alice", "Portevent" ]
presentationArray = nameArray.map(name => "My name is " + name)
// presentationArray = [ "My name is George", "My name is Alice", "My name is Portevent" ]
nameArray.map will iterate on each element. name will be equal to "George", then "Alice" etc...
Foreach element, it will be replaced with "My name is " + name (remember, name will have each different value).
Note : .map doesn't change the initial array, it just create another array (so we save it inside presentationArray
A more advanced use of map :
numbers = [1, 2, 3]
function tenToPower(n) {
return 10 ** n
}
numbers.map(number => tenToPower) // [10, 100, 1000]
numbers.map(number => {
if (number < 3) return "Failed"
else return "Valid"
}) // ["Failed", "Failed", "Valid"]
const item = data.map((user) => {
if(user.username === 'Bret'){
setName(user.name);
setUserName(user.username);
setId(user.id)
}
})

python how to get dictionally object in json?

I start learning json. I can access title object like this
json_data = results['local_results']
for i in json_data:
if "title" in i:
title = i["title"]
How to accesss latitude object of gps_coordinates, website object of links.
here is my json data.
"local_results": [
{
"position": 1,
"title": "McDonald's",
"place_id": "2142927458143177356",
"lsig": "AB86z5W5r155sIcs3jqfYkm9Y8Fp",
"place_id_search": "https://serpapi.com/search.json?device=desktop&engine=google&gl=us&google_domain=google.com&hl=en&location=austin%2C+texas%2C+united+states&lsig=AB86z5W5r155sIcs3jqfYkm9Y8Fp&ludocid=2142927458143177356&q=McDonald%27s&tbm=lcl&token=16c37bb72affc4f2",
"address": "Austin, TX",
"phone": "(512) 442-0412",
"hours": "Open ⋅ Closes 12AM",
"gps_coordinates": {
"latitude": 30.260337999999994,
"longitude": -97.7581347
},
"links": {
"website": "https://www.mcdonalds.com/us/en-us/location/TX/AUSTIN/1209-BARTON-SPRINGS/4941.html?cid=RF:YXT:GMB::Clicks",
"directions": "https://www.google.com/maps/dir//McDonald's,+1209+Barton+Springs+Rd,+Austin,+TX+78704/data=!4m6!4m5!1m1!4e2!1m2!1m1!1s0x8644b51bd54fc423:0x1dbd352b620e0a8c?sa=X&hl=en"
}
},
Json data:
x = {"local_results": [
{
"position": 1,
"title": "McDonald's",
"place_id": "2142927458143177356",
"lsig": "AB86z5W5r155sIcs3jqfYkm9Y8Fp",
"place_id_search": "https://serpapi.com/search.json?device=desktop&engine=google&gl=us&google_domain=google.com&hl=en&location=austin%2C+texas%2C+united+states&lsig=AB86z5W5r155sIcs3jqfYkm9Y8Fp&ludocid=2142927458143177356&q=McDonald%27s&tbm=lcl&token=16c37bb72affc4f2",
"address": "Austin, TX",
"phone": "(512) 442-0412",
"hours": "Open ⋅ Closes 12AM",
"gps_coordinates": {
"latitude": 30.260337999999994,
"longitude": -97.7581347
},
"links": {
"website": "https://www.mcdonalds.com/us/en-us/location/TX/AUSTIN/1209-BARTON-SPRINGS/4941.html?cid=RF:YXT:GMB::Clicks",
"directions": "https://www.google.com/maps/dir//McDonald's,+1209+Barton+Springs+Rd,+Austin,+TX+78704/data=!4m6!4m5!1m1!4e2!1m2!1m1!1s0x8644b51bd54fc423:0x1dbd352b620e0a8c?sa=X&hl=en"
}
}]}
Coordinates extraction:
x['local_results'][0]['gps_coordinates']
Ouput:
{'latitude': 30.260337999999994, 'longitude': -97.7581347}
Website extraction:
print(x['local_results'][0]['links']['website'])
output:
https://www.mcdonalds.com/us/en-us/location/TX/AUSTIN/1209-BARTON-SPRINGS/4941.html?cid=RF:YXT:GMB::Clicks
Here is your JSON data:
data = {"local_results": [
{
"position": 1,
"title": "McDonald's",
"place_id": "2142927458143177356",
"lsig": "AB86z5W5r155sIcs3jqfYkm9Y8Fp",
"place_id_search": "https://serpapi.com/search.json?device=desktop&engine=google&gl=us&google_domain=google.com&hl=en&location=austin%2C+texas%2C+united+states&lsig=AB86z5W5r155sIcs3jqfYkm9Y8Fp&ludocid=2142927458143177356&q=McDonald%27s&tbm=lcl&token=16c37bb72affc4f2",
"address": "Austin, TX",
"phone": "(512) 442-0412",
"hours": "Open ⋅ Closes 12AM",
"gps_coordinates": {
"latitude": 30.260337999999994,
"longitude": -97.7581347
},
"links": {
"website": "https://www.mcdonalds.com/us/en-us/location/TX/AUSTIN/1209-BARTON-SPRINGS/4941.html?cid=RF:YXT:GMB::Clicks",
"directions": "https://www.google.com/maps/dir//McDonald's,+1209+Barton+Springs+Rd,+Austin,+TX+78704/data=!4m6!4m5!1m1!4e2!1m2!1m1!1s0x8644b51bd54fc423:0x1dbd352b620e0a8c?sa=X&hl=en"
}
}]}
You enter JSON information into this website (http://jsonviewer.stack.hu/) and you see your data regularly and you can easily access it.
so, here you can access the link and gps_coordinates this way:
print(data['local_results'][0]['gps_coordinates'])
print(data['local_results'][0]['links'])

How we can show collection data in array

When I am using get api and get the data in json format
{
"uuid": "46d00217-6e35-485c-ac20-c204a8a24a68",
"name": "AMan",
"dispute_location": "Hyder",
"max_dispute_value": "200",
"min_dispute_value": "100",
"state": "U.p",
"district": "morene",
"calendar_id": "3",
"description": null,
"subject_matters": [
{
"id": 1,
"name": "A",
"created_at": "2020-08-14T12:24:52.000000Z",
"updated_at": "2020-08-14T12:24:52.000000Z",
"pivot": {
"court_uuid": "46d00217-6e35-485c-ac20-c204a8a24a68",
"subject_matter_id": 1
}
},
{
"id": 2,
"name": "B",
"created_at": "2020-08-14T12:24:57.000000Z",
"updated_at": "2020-08-14T12:24:57.000000Z",
"pivot": {
"court_uuid": "46d00217-6e35-485c-ac20-c204a8a24a68",
"subject_matter_id": 2
}
}
]
}
but i want subject_matters data in this format
"subject_matters": [1,2]
Api resource (court resources)
You can use ->pluck('id'); in your resource.
return [
'subject_matters_id' => $this->subjectMatters->pluck('id')
]
It should return an array of subject matter IDs.

How to create a JSON structure in ReactJS

I have a use-case to create a JSON structure in React in order to POST an API request. The JSON structure body contains objects and arrays.
Please let me know how to create it in ReactJS.
Below is the sample JSON structure that needs to be created using ReactJS:-
{
"transactionAmount": {
"currency": "INR",
"value": 1220.38
},
"transactionDate": "2020-05-18T00:00:00Z",
"tripData": {
"agencyBooked": false,
"legs": [
{
"endLocation": {
"countryCode": "IN",
"city": "Delhi",
"name": "Indira Gandhi International"
},
"startDate": "2020-05-22",
"startTime": "08:00",
"returnLeg": false,
"startLocation": {
"countryCode": "US",
"city": "San Francisco",
"name": "San Francisco International"
},
"endTime": "21:00",
"endDate": "2020-05-22",
"startLocationDetail": "none"
},
{
"endLocation": {
"countryCode": "US",
"city": "San Francisco",
"name": "San Francisco International"
},
"returnLeg": true,
"startDate": "2020-05-24",
"startLocation": {
"countryCode": "IN",
"city": "Delhi",
"name": "Indira Gandhi International"
},
"startTime": "17:00"
}
],
"segmentType": {
"category": "REQ_SEG_AIRFR",
"code": "AIRFR"
},
"selfBooked": false,
"tripType": "ROUND_TRIP"
}
}
You can simply make a JSON format like this.
const dummyObject = {
name: 'Dummy',
age: 22,
about: {
hobbies: ['soccer']
},
works: true
}

how can i return fetch() in map() loop

I wrote a webapp about weather and i used weatherbit api that is just free part. i want to fetch() funk in map() loop .
i have an object which has cityname and country name . map() return every cityname and country with fetch()
how can i do that?
one more question every step of map() loop i get one JSON .. Maybe and of the loop i have 10 JSON... How can i match all Json into one Json?
here is the code..
const cityName = [
{
"id": 1,
"name": "Ingolstadt",
"country": "GE",
},
{
"id": 2,
"name": "Vienna",
"country": "AT",
},
{
"id": 3,
"name": "Istanbul",
"country": "TR",
},
{
"id": 4,
"name": "London",
"country": "GB",
},
{
"id": 5,
"name": "Ankara",
"country": "TR",
},
{
"id": 6,
"name": "Paris",
"country": "FR",
},
{
"id": 7,
"name": "Barcelona",
"country": "ES",
},
{
"id": 8,
"name": "Amsterdam",
"country": "NL",
},
{
"id": 9,
"name": "Belgrade",
"country": "RS",
},
{
"id": 10,
"name": "Munich",
"country": "GE",
}
]
//should return all city which are in object
const citySource = cityName.map((name , country) => {
// get api from weatherbit api , but i dont know ${name} and ${country} right sycntax
fetch(`https://api.weatherbit.io/v2.0/current?city=${name}&country=${country}&key=86e622607fbe4c2cb9f7f71889a4d48d`)
.then(response => response.json())
.then( users => console.log(users));
})
According to MDN:
The map() method creates a new array with the results of calling a provided function on every element in the calling array.
Here you have working example:
const cityName = [
{
"id": 1,
"name": "Ingolstadt",
"country": "GE",
},
{
"id": 2,
"name": "Vienna",
"country": "AT",
},
{
"id": 3,
"name": "Istanbul",
"country": "TR",
},
{
"id": 4,
"name": "London",
"country": "GB",
},
{
"id": 5,
"name": "Ankara",
"country": "TR",
},
{
"id": 6,
"name": "Paris",
"country": "FR",
},
{
"id": 7,
"name": "Barcelona",
"country": "ES",
},
{
"id": 8,
"name": "Amsterdam",
"country": "NL",
},
{
"id": 9,
"name": "Belgrade",
"country": "RS",
},
{
"id": 10,
"name": "Munich",
"country": "GE",
}
]
//should return all city which are in object
const citySource = cityName.map((city) => {
fetch(`https://api.weatherbit.io/v2.0/current?city=${city.name}&country=${city.country}&key=86e622607fbe4c2cb9f7f71889a4d48d`)
.then(response => response.json())
.then( users => console.log(users));
})

Resources