Calling an api and getting the response in xml. I am trying to convert the xml output to JSON using xml2json. How can now i read directly the temperature parameter value from the json output.
I am using following in my code,
var xml = response.body;
var result = convert.xml2json(xml, {compact: true, spaces: 4});
const jsonData = JSON.parse(result);
res.send(jsonData);
jsonData has all data but i just want to read e.g temperature value
Here is the json output after conversion,
{
"_declaration": {
"_attributes": {
"version": "1.0",
"encoding": "UTF-8"
}
},
"wfs:FeatureCollection": {
"_attributes": {
"timeStamp": "2019-05-02T17:21:05Z",
"numberReturned": "864",
"numberMatched": "864",
"xmlns:wfs": "http://www.opengis.net/wfs/2.0",
"xmlns:gml": "http://www.opengis.net/gml/3.2",
"xmlns:BsWfs": "http://xml.fmi.fi/schema/wfs/2.0",
"xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
"xsi:schemaLocation": "http://www.opengis.net/wfs/2.0
http://schemas.opengis.net/wfs/2.0/wfs.xsd\n
http://xml.fmi.fi/schema/wfs/2.0
http://xml.fmi.fi/schema/wfs/2.0/fmi_wfs_simplefeature.xsd"
},
"wfs:member": [
{
"BsWfs:BsWfsElement": {
"_attributes": {
"gml:id": "BsWfsElement.1.1.1"
},
"BsWfs:Location": {
"gml:Point": {
"_attributes": {
"gml:id": "BsWfsElementP.1.1.1",
"srsDimension": "2",
"srsName": "http://www.opengis.net/def/crs/EPSG/0/4258"
},
"gml:pos": {
"_text": "60.20520 24.65220 "
}
}
},
"BsWfs:Time": {
"_text": "2019-05-02T18:00:00Z"
},
"BsWfs:ParameterName": {
"_text": "GeopHeight"
},
"BsWfs:ParameterValue": {
"_text": "36.57"
}
}
},
{
"BsWfs:BsWfsElement": {
"_attributes": {
"gml:id": "BsWfsElement.1.1.2"
},
"BsWfs:Location": {
"gml:Point": {
"_attributes": {
"gml:id": "BsWfsElementP.1.1.2",
"srsDimension": "2",
"srsName":
"http://www.opengis.net/def/crs/EPSG/0/4258"
},
"gml:pos": {
"_text": "60.20520 24.65220 "
}
}
},
"BsWfs:Time": {
"_text": "2019-05-02T18:00:00Z"
},
"BsWfs:ParameterName": {
"_text": "Temperature"
},
"BsWfs:ParameterValue": {
"_text": "2.97"
}
}
}
]
}
}
jsonData['wfs:FeatureCollection']['wfs:member'][0]['BsWfs:BsWfsElement']['BsWfs:ParameterName']['_text']
ex)
jsonData = { "key0": 34 }
jsonArray = [ 35,36,37 ]
=>
console.log(jsonData['key0"]); // 34
console.log(jsonArray[0]); // 35
Related
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 14 days ago.
Using dot notation to access a JSON response is returning different values than what the API response is saying in my browser
I tried to access a JSON response from an axios request like so:
const response = await axios.get('https://store-site-backend-static.ak.epicgames.com/freeGamesPromotions?locale=en-US&country=US&allowCountries=US');
console.log(response.data.data.Catalog.searchStore.elements.promotions)
Instead of getting a response something similar to this in JSON:
{
"promotions": {
"promotionalOffers": [
{
"promotionalOffers": [
{
"startDate": "2023-02-02T16:00:00.000Z",
"endDate": "2023-02-09T16:00:00.000Z",
"discountSetting": {
"discountType": "PERCENTAGE",
"discountPercentage": 0
}
}
]
}
],
"upcomingPromotionalOffers": []
}
}
I simply get this from the console log:
undefined
undefined
undefined
undefined
undefined
I might not be using dot notation to access it correctly but I have no idea. You can view the JSON response from the browser here: https://store-site-backend-static.ak.epicgames.com/freeGamesPromotions?locale=en-US&country=US&allowCountries=US
#1 Getting data from the server by axios.
The elements start [ and end ] is an array data.
(* I copy/paste from Browser to VS code after access URL, saved JSON data)
VS code can expand/collapse data by clicking down arrow.
#2 Filter only promotions
It is one of Key values of array elements
You can filter by Array map()
Simple example for getting title only
const titles = elements.map(item => { return { title : item.title } } )
console.log(JSON.stringify(titles, null, 4))
[
{
"title": "Borderlands 3 Season Pass"
},
{
"title": "City of Gangsters"
},
{
"title": "Recipe for Disaster"
},
{
"title": "Dishonored®: Death of the Outsider™"
},
{
"title": "Dishonored - Definitive Edition"
}
]
So this code will works for getting promotions
const axios = require('axios')
const getPromotions = async (data) => {
try {
const response = await axios.get('https://store-site-backend-static.ak.epicgames.com/freeGamesPromotions?locale=en-US&country=US&allowCountries=US');
return Promise.resolve(response.data)
} catch (error) {
return Promise.reject(error)
}
};
getPromotions()
.then(result => {
const promotions = result.data.Catalog.searchStore.elements.map(item => { return { promotions : item.promotions } } )
console.log(JSON.stringify(promotions, null, 4))
})
.catch(error => {
console.log(error.message)
});
Result
$ node get-data.js
[
{
"promotions": {
"promotionalOffers": [
{
"promotionalOffers": [
{
"startDate": "2023-01-26T16:00:00.000Z",
"endDate": "2023-02-09T16:00:00.000Z",
"discountSetting": {
"discountType": "PERCENTAGE",
"discountPercentage": 30
}
},
{
"startDate": "2023-01-26T16:00:00.000Z",
"endDate": "2023-02-09T16:00:00.000Z",
"discountSetting": {
"discountType": "PERCENTAGE",
"discountPercentage": 30
}
}
]
}
],
"upcomingPromotionalOffers": []
}
},
{
"promotions": {
"promotionalOffers": [
{
"promotionalOffers": [
{
"startDate": "2023-02-02T16:00:00.000Z",
"endDate": "2023-02-09T16:00:00.000Z",
"discountSetting": {
"discountType": "PERCENTAGE",
"discountPercentage": 0
}
}
]
}
],
"upcomingPromotionalOffers": []
}
},
{
"promotions": {
"promotionalOffers": [],
"upcomingPromotionalOffers": [
{
"promotionalOffers": [
{
"startDate": "2023-02-09T16:00:00.000Z",
"endDate": "2023-02-16T16:00:00.000Z",
"discountSetting": {
"discountType": "PERCENTAGE",
"discountPercentage": 0
}
}
]
}
]
}
},
{
"promotions": {
"promotionalOffers": [
{
"promotionalOffers": [
{
"startDate": "2023-02-02T16:00:00.000Z",
"endDate": "2023-02-09T16:00:00.000Z",
"discountSetting": {
"discountType": "PERCENTAGE",
"discountPercentage": 0
}
}
]
}
],
"upcomingPromotionalOffers": []
}
},
{
"promotions": null
}
]
I am using includeArrayIndex to add the rank based on sorting
Here is the aggregation query
dbo.collection("funds").aggregate([
{
"$sort": {
"amount": -1
}
},
{
"$group": {
"_id": "",
"items": {
"$push": "$$ROOT"
}
}
},
{
"$unwind": {
"path": "$items",
"includeArrayIndex": "items.rank"
}
},
{
"$replaceRoot": {
"newRoot": "$items"
}
},
{
"$sort": {
"rank": -1
}
}
])
and this assign the rank field but starting from 0, is there any way to start it from 1
tried with set like this
[
{
'$sort': {
'amount': -1
}
}, {
'$group': {
'_id': '',
'items': {
'$push': '$$ROOT'
}
}
}, {
'$unwind': {
'path': '$items',
'includeArrayIndex': 'items.rank'
}
}, {
'$replaceRoot': {
'newRoot': '$items'
}
},
{
'$set': {
'rank': {
'$add': [
'$rank', 1
]
}
}
},
// {
// '$sort': {
// 'rank': 1
// }
// }
]
in the mongodb compass aggregation tab it shows that field got added but when i run this script using nodejs it does not add the rank field
even i tried with
const a = await dbo.collection("funds").aggregate(
[
{
'$sort': {
'amount': 1
}
}, {
'$group': {
'_id': '',
'items': {
'$push': '$$ROOT'
}
}
}, {
'$unwind': {
'path': '$items',
'includeArrayIndex': 'items.rank'
}
}, {
'$replaceRoot': {
'newRoot': '$items'
}
},
{
'$addFields': {
'rank': {
'$add': [
'$rank', 1
]
}
}
}
]
).toArray();
and this even prints on console as a
[
{ _id: new ObjectId("6220d2fe20e33d48c865b720"), amount: 1, rank: 1 },
{
_id: new ObjectId("6220d2cf20e33d48c865b71e"),
amount: 10,
rank: 2
},
{
_id: new ObjectId("6220d2f520e33d48c865b71f"),
amount: 12,
rank: 3
}
]
and then tried with $setWindowFields
dbo.collection("funds").aggregate( [
{
$setWindowFields: {
sortBy: { amount: -1 },
output: {
rank: {
$rank: {}
}
}
}
}
] )
but it shows
err MongoServerError: Unrecognized pipeline stage name: '$setWindowFields'
Sample document is like
[
{amount : 20, name :""},
{amount : 22, name :""}
]
Not sure if this was already answered. But you just have to add { $out: "funds" }
at the last of your code. PFB the working code ...
const a = await dbo.collection("funds").aggregate(
[
{
'$sort': {
'amount': 1
}
}, {
'$group': {
'_id': '',
'items': {
'$push': '$$ROOT'
}
}
}, {
'$unwind': {
'path': '$items',
'includeArrayIndex': 'items.rank'
}
}, {
'$replaceRoot': {
'newRoot': '$items'
}
},
{
'$addFields': {
'rank': {
'$add': [
'$rank', 1
]
}
}
},
{ $out: "funds" }
], {allowDiskUse:true}
).toArray();
I have an array that looks like below:
[
{ "name":"ABC", "group":"A" },
{ "name":"XYZ", "group":"A" },
{ "name":"KLP", "group":"A" },
{ "name":"AKG", "group":"B" },
{ "name":"DIS", "group":"B" },
{ "name":"FAC", "group":"B" },
{ "name":"TAM", "group":"B" },
{ "name":"NEW", "group":"C" },
{ "name":"UTL", "group":"C" },
{ "name":"WAC", "group":"C" }
]
How can I sort this by group in angular
I want result like below
{
"A":[ "ABC", "XYZ", "KLP" ],
"B":[ "AKG", "DIS", "FAC", "TAM" ],
"C":[ "NEW", "UTL", "WAC" ]
}
Please help me to do so
Thanks in advance
const sortedData: any = {};
for (const d of this.data) {
sortedData[d.group] ? sortedData[d.group].push(d.name) : sortedData[d.group] = [d.name];
}
In my MongoDB database, I have a collection 'produits' with documents like this
{
"_id": {
"$oid": "6048e97b4a5f000096007505"
},
"modeles": [
{
"id": "OppoA3",
"pieces": [
{
"id": "OppoA3avn"
},
{
"id": "OppoA3bat"
}]
]
},
{
"id": "OppoA1",
"pieces": [
{
"id": "OppoA1avn",
},
{
"id": "OppoA1batt",
}
]
}
]
}
How can I delete all modeles.pieces from all my documents.
I managed to delete with a filter on modeles.id but with that code but not on all the collection
db.produits.update(
{marque_id:'OPPO', 'modeles.id':'RENOZ'},
{$set:
{
'modeles.$.pieces': []
}
}
, { multi : true }
)
I would like all documents like this finally
{
"_id": {
"$oid": "6048e97b4a5f000096007505"
},
"modeles": [
{
"id": "OppoA3",
"pieces": []
},
{
"id": "OppoA1",
"pieces": []
}
]
}
Thank you for your help.
I have done a javascript loop like this, but i think it's not best practice
async removePieces(){
var doc
try {
doc = await produitModel.find()
for (var produit of doc) {
for (var modele of produit.modeles) {
const filter = {'marque_id': produit.marque_id, 'modeles.id': modele.id}
const set = {
$set: {
'modeles.$.pieces': []
}
}
await db.collection('produits').updateOne(filter, set)
}
}
console.log('removePieces() ==> Terminé')
} catch(err) {
console.log(err)
}
}
db.produits.update({
modeles: {//This is because your second document will create failure otherwise
$exists: true
}
},
{
$set: {
"modeles.$.pieces": []
}
},
{
multi: true
})
//Existing Json that i have
[
{
"Id":1,
"Authors":[
{
"Id":10,
"Name":"Arun"
},
{
"Id":14,
"Name":"Arjun"
}
],
"tags":[
{
"Name":"Java"
}
]
},
{
"Id":5,
"Authors":[
{
"Id":7,
"Name":"Shyama"
}
],
"tags":[
{
"Name":"C#"
},
{
"Name":"C++"
}
]
}
]
//New Json (converted)
//Here i want to combine both the author
[
{
"Id":1,
"Authors":"Arun, Arjun",
"tags":"Java"
},
{
"Id":5,
"Authors":"Shyama",
"tags":"C#,C++"
}
]
//Controller that i have created
$scope.request = response.data;//request contain all json data
//---------- logic to create new json------------
}
var json = [
{
"Id":1,
"Authors":[
{
"Id":10,
"Name":"Arun"
},
{
"Id":14,
"Name":"Arjun"
}
],
"tags":[
{
"Name":"Java"
}
]
},
{
"Id":5,
"Authors":[
{
"Id":7,
"Name":"Shyama"
}
],
"tags":[
{
"Name":"C#"
},
{
"Name":"C++"
}
]
}
];
for (var i=0, j=json.length; i<j; i++) {
json[i].Authors = json[i].Authors.map(function(item) {return item.Name;}).join(',');
json[i].tags = json[i].tags.map(function(item) {return item.Name;}).join(',');
}
console.log(json);