JSON dot notation returning different from JSON api request [duplicate] - arrays

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
}
]

Related

How to delete all sub array

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
})

How do I sort this array by date?

I'm trying to sort the dates from this external API in my latestResults array by latest on top to oldest on bottom but can't seem to figure out how.
Right now they're displayed with the oldest date first and it's working fine, but it's in the wrong order for me.
I tried using result in latestResults.reverse() but that just reverses the 7 items currently in the array.
HTML:
<div v-for="result in latestResults" v-bind:key="result.latestResults">
<small">{{ result.utcDate }}</small>
</div>
Script:
<script>
import api from '../api'
export default {
data () {
return {
latestResults: [],
limit: 7,
busy: false,
loader: false,
}
},
methods: {
loadMore() {
this.loader = true;
this.busy = true;
api.get('competitions/PL/matches?status=FINISHED')
.then(response => { const append = response.data.matches.slice(
this.latestResults.length,
this.latestResults.length + this.limit,
this.latestResults.sort((b, a) => {
return new Date(b.utcDate) - new Date(a.utcDate);
})
);
setTimeout(() => {
this.latestResults = this.latestResults.concat(append);
this.busy = false;
this.loader = false;
}, 500);
});
}
},
created() {
this.loadMore();
}
}
</script>
The JSON where I'm getting matches like this that has utcDate:
{
"count": 205,
"filters": {
"status": [
"FINISHED"
]
},
"competition": {
"id": 2021,
"area": {
"id": 2072,
"name": "England"
},
"name": "Premier League",
"code": "PL",
"plan": "TIER_ONE",
"lastUpdated": "2021-02-01T16:20:10Z"
},
"matches": [
{
"id": 303759,
"season": {
"id": 619,
"startDate": "2020-09-12",
"endDate": "2021-05-23",
"currentMatchday": 22
},
"utcDate": "2020-09-12T11:30:00Z",
"status": "FINISHED",
"matchday": 1,
"stage": "REGULAR_SEASON",
"group": "Regular Season",
"lastUpdated": "2020-09-13T00:08:13Z",
"odds": {
"msg": "Activate Odds-Package in User-Panel to retrieve odds."
},
},

Logic App - Refer and map fields on different JSON data sources

I have two JSON data sources:
Source Data 1:
{
"result": [
{
"resource_list": "7961b907db9253045fbdf1fabf9619d4,55617907db9253045fbdf1fabf9619d2",
"project": "11216",
"project_manager": {
"value": "55617907db9253045fbdf1fabf9619d2"
}
}
]
}
Source Data 2:
{
"result": [
{
"sys_id": "7961b907db9253045fbdf1fabf9619d4",
"email": "test.user1#mysite.com"
},
{
"sys_id": "55617907db9253045fbdf1fabf9619d2",
"email": "test.user2#mysite.com"
}
]
}
I want to reference "resource_list" and "project_manager" from Source Data 1 to "sys_id" in Source Data 2 and get "email" out from Source Data 2 and then compose a final Output like below:
Output:
[
{
"__metadata":
{
"uri": "ProjectCode"
},
"externalProject": "11216",
"projectCodeAssignment":
[
{
"__metadata":
{
"uri": "projectCodeAssignment"
},
"externalProjectAssignee": "test.user1#mysite.com"
},
{
"__metadata":
{
"uri": "projectCodeAssignment"
},
"externalProjectAssignee": "test.user2#mysite.com"
}
]
}
]
Is this possible to get this done entirely in Logic App without using Function App or anything to perform it rather.
I write a js script for you. For a quick demo, I omitted some data related to __metadata, seems that is some hard code, not so important here. Try Logic below:
Code in JS code action:
var body = workflowContext.trigger.outputs.body
var data1 = body.data1;
var data2 = body.data2;
var result = [];
data1.result.forEach(item =>{
var resultItem = {};
resultItem.externalProject = item.project;
resultItem.projectCodeAssignment =[];
var resourceIds = item.resource_list.split(',');
resourceIds.forEach(id =>{
var user = data2.result.find( ({ sys_id }) => sys_id === id );
resultItem.projectCodeAssignment.push({"externalProjectAssignee": user.email})
});
result.push(resultItem);
})
return result;
Request Body(your 2 data set are named as data1 and data2 here ):
{
"data1": {
"result": [{
"resource_list": "7961b907db9253045fbdf1fabf9619d4,55617907db9253045fbdf1fabf9619d2",
"project": "11216",
"project_manager": {
"value": "55617907db9253045fbdf1fabf9619d2"
}
}
]
},
"data2": {
"result": [{
"sys_id": "7961b907db9253045fbdf1fabf9619d4",
"email": "test.user1#mysite.com"
}, {
"sys_id": "55617907db9253045fbdf1fabf9619d2",
"email": "test.user2#mysite.com"
}
]
}
}
Result:

Parsing JSON after conversion using XML2JSON

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

Response duplicated but the count shows as 1

Using Dynamoose ORM with Serverless. I have a scenario where I'm finding user information based on recommendation.
The response is as follows
{
"data": {
"results": [
{
"specialTip": "Hello World",
"recommendation": "Huli ka!",
"poi": {
"uuid": "poi_555",
"name": "Bukit Panjang",
"images": [
{
"url": "facebook.com",
"libraryUuid": "2222",
"uuid": "9999"
}
]
},
"uuid": "i_8253578c-600d-4dfd-bd40-ce5b9bb89067",
"headline": "Awesome",
"dataset": "attractions",
"insiderUUID": "i_c932e85b-0aee-4462-b930-962f555b64bd",
"insiderInfo": [
{
"gender": "m",
"funFacts": [
{
"type": "knock knock!",
"answer": "Who's there?"
}
],
"profileImage": "newImage.jpg",
"shortDescription": "Samething",
"fullDescription": "Whatever Description",
"interests": [
"HELLO",
"WORLD"
],
"tribes": [
"HELLO",
"WORLD"
],
"uuid": "i_c932e85b-0aee-4462-b930-962f555b64bd",
"personalities": [
"HELLO",
"WORLD"
],
"travelledCities": [
"HELLO",
"WORLD"
]
}
]
},
{
"specialTip": "Hello World",
"recommendation": "Huli ka!",
"poi": {
"uuid": "poi_555",
"name": "Bukit Panjang",
"images": [
{
"url": "facebook.com",
"libraryUuid": "2222",
"uuid": "9999"
}
]
},
"uuid": "i_8253578c-600d-4dfd-bd40-ce5b9bb89067",
"headline": "Awesome",
"dataset": "attractions",
"insiderUUID": "i_c932e85b-0aee-4462-b930-962f555b64bd",
"insiderInfo": [
{
"gender": "m",
"funFacts": [
{
"type": "knock knock!",
"answer": "Who's there?"
}
],
"profileImage": "newImage.jpg",
"shortDescription": "Samething",
"fullDescription": "Whatever Description",
"interests": [
"HELLO",
"WORLD"
],
"tribes": [
"HELLO",
"WORLD"
],
"uuid": "i_c932e85b-0aee-4462-b930-962f555b64bd",
"personalities": [
"HELLO",
"WORLD"
],
"travelledCities": [
"HELLO",
"WORLD"
]
}
]
}
],
"count": 1
},
"statusCode": 200
}
Not sure where I'm going wrong as the items in the response seems to be duplicated but the count is 1.
Here is the code
module.exports.index = (_event, _context, callback) => {
Recommendation.scan().exec((_err, recommendations) => {
if (recommendations.count == 0) {
return;
}
let results = [];
recommendations.forEach((recommendation) => {
Insider.query({uuid: recommendation.insiderUUID}).exec((_err, insider) => {
if (insider.count == 0) {
return;
}
recommendation.insiderInfo = insider;
results.push(recommendation);
});
});
const response = {
data: {
results: results,
count: results.count
},
statusCode: 200
};
callback(null, response);
});
};
EDIT: My previous code ignored the fact that your "Insider" query is asynchronous. This new code handles that and matches your edit.
const async = require('async'); // install async with 'npm install --save async'
[...]
module.exports.index = (_event, _context, callback) => {
Recommendation.scan().exec((_err, recommendations) => {
if (_err) {
console.log(_err);
return callback(_err);
}
if (recommendations.count == 0) {
const response = {
data: {
results: [],
count: 0
},
statusCode: 200
};
return callback(null, response);
}
let results = [];
async.each(recommendations, (recommendation, cb) => { // We need to handle each recommendation asynchronously...
Insider.query({uuid: recommendation.insiderUUID}).exec((_err, insider) => { // because this is asynchronous
if (_err) {
console.log(_err);
return callback(_err);
}
if (insider.count == 0) {
return cb(null);
}
recommendation.insiderInfo = insider;
results.push(recommendation);
return cb(null);
});
}, (err) => { // Once all items are handled, this is called
if (err) {
console.log(err);
return callback(err);
}
const response = { // We prepare our response
data: {
results: results, // Results may be in a different order than in the initial `recommendations` array
count: results.count
},
statusCode: 200
};
callback(null, response); // We call our main callback only once
});
});
};
Initial (partly incorrect) answer, for reference.
You are pushing the result of your mapping into the object that you are currently mapping and callback is called more than once here. That's a pretty good amount of unexpected behavior material.
Try the following:
let results = [];
recommendations.forEach((recommendation) => {
Insider.query({uuid: recommendation.insiderUUID}).exec((_err, insider) => {
if (insider.count == 0) {
return;
}
recommendation.insiderInfo = insider;
results.push(recommendation);
});
});
let response = {
data: {
results: results,
count: results.count
},
statusCode: 200
};
callback(null, response);

Resources