I am working on some trains' open data feed and getting some JSON as a response from a server. I parse this JSON into a data variable and display it as seen below. However, I cannot find a way to iterate over the response to be able to manipulate each message. I want to iterate over each message and then use the data for a record in a SQL database. I cannot get to the point of accessing any individual message data.
How can I create a loop to iterate over each message and extract it's data?
[
{
SF_MSG: {
time: '1666370311000',
area_id: 'TD',
address: '0C',
msg_type: 'SF',
data: '1F'
}
},
{
CA_MSG: {
to: '4333',
time: '1666370311000',
area_id: 'WO',
msg_type: 'CA',
from: '4331',
descr: '2K60'
}
}, ...
]
Edit: using data.forEach(function(message) produces an output of the structure:
{ CA_MSG: { to: '6021', time: '1666372120000', area_id: 'CY', msg_type: 'CA', from: 'STIN', descr: '2Y73' } }
, however, how do I query this inner object, the names of the objects will differ depending on message type if this matters?
try this:
data = JSON.parse(yourJSONdata)
data.map((o, i)=>{
//o is the object, i is the index
// do your processing here
then at the end do
data[i]=processedobject
})
Related
have a mongo database which holds a short list of events with some extra data. The data is returned and sent to the App. This all goes swimmingly. Inside the App I want to extract titles foreach array element, but when i try use or foreach loop the output is undefinded.
** data i get from api:**
{status: 'ok', evnets: Array(1)} evnets: Array(1) 0 {title: 'r', descryption: 'asd', StartDate: '2022-12-16 13:51', EndDate: '2022-12-29 09:52', _id: '63944787606e1280f2e14cde'}
I tried:
foreach()
data.events.forEach(element => {
Title = data.events.title
});
I think the returned data from the API is evnets not events
Hello I would like to know if there would be a method to recover the uuid when I push data in my table I put you in the screenshot below
the code
push(ref(db, `/users/${auth.currentUser.uid}/user/sensors`), {
name: registerInformation.nameBox,
id: registerInformation.idBox,
categories: registerInformation.categories,
routine: registerInformation.routine,
});
The push function returns a Reference object, from which you can get the key with something like this:
const newRef = push(ref(db, `/users/${auth.currentUser.uid}/user/sensors`), {
name: registerInformation.nameBox,
id: registerInformation.idBox,
categories: registerInformation.categories,
routine: registerInformation.routine,
});
console.log(newRef.key);
If you want to use that key in the write operation, you can also separate the creating of the new ID from the writing of the data like this:
const newRef = push(ref(db, `/users/${auth.currentUser.uid}/user/sensors`));
console.log(newRef.key);
set(newRef, {
name: registerInformation.nameBox,
id: registerInformation.idBox,
categories: registerInformation.categories,
routine: registerInformation.routine,
});
In this snippet, the first line is a pure client-side operation that doesn't actually write anything to the database yet.
Axios sends an array of strings instead of an array of objects. I have an array of objects that contains data about the event. I'm trying to send a request to the server via axios, but I get a array of strings insteenter image description heread of objects at the output
let data = {
title: 'Game',
subject: 'Some subject',
date: ['01/01/2021','01/01/2021'],
years: ['1970', '1970'],
address: 'None',
ages: [
{
title: 'Men',
weights: [{page: 0, title: '60'}]
}
]
};
api.Create({
params: data
}).then(function (response) {
console.log(response.data);
})
.catch(function (err) {
console.log(err);
});
api response
try to:
console.log(JSON.parse(response.data))
What you get back from the server is string. you need to parse it.
When you send data to and from a server, it is sent as a 'serialized' string, usually JSON format
That's how server responses work
It turned out to be an incorrect request. I used GET to pass the object, instead of POST, so it converts it to a string. I want to notice that there is an evil community on this site.
I am trying to get a json object like the below
{
"Name":"UnitedStates",
"Info":[
{"StateName":"Washington",
"Commands":[
{"Type":"Men","Parameter":"10000"},
{"Type":"Women","Parameter":"30000"}
]},
{"StateName":"California",
"Commands":[
{"Type":"Kids","Parameter":"20000"}
]}
]}
I am trying the below
Fiddle
How can I add array of values to existing blank object.
var CountryName = 'UnitedStates';
var Data = {
Name: CountryName,
Info: [
commands :[]
]
}
Data.Info.push({'StateName': 'washington'});
Data.Info.commands.push(
{'Type': 'Men'},
{'Parameter': '1000'},
);
$('.displayJsonBlock').empty();
$('.displayJsonBlock').append('<pre><code>' + JSON.stringify(TemplateData) + '</pre></code>')
If you look at the error console output, you'll see it's giving you a syntax error because Info is trying to be both an object and an array at the same time:
Info: [
commands :[]
]
If you want to push into Info it needs to be an array, but that means you can't define properties in the literal like this. If you want to define properties like this it needs to be a an object like:
Info: {
commands :[]
}
But then you can't push.
I think what you're looking for is:
var CountryName = 'UnitedStates';
var Data = {
Name: CountryName,
Info: [] // info is just an array
}
Data.Info.push({
'StateName': 'washington',
commands: [] // each element of Info is an object with a commands array
});
Data.Info[0].commands.push( // you need to define which element of info. Here it's the first
{'Type': 'Men'},
{'Parameter': '1000'},
);
console.log(Data)
Of course you don't need to do two pushes you can push the whole object including commands:
Data.Info.push({
'StateName': 'washington',
commands: [
{'Type': 'Men'},
{'Parameter': '1000'}
]
})
Well, the structure of JSON data is incorrect, I think you do something like this
var CountryName = 'UnitedStates';
var Data = {
Name: CountryName,
Info: [
{commands :[]}
]
}
After
Data.Info.push({'StateName': 'washington'});
Data.Info['commands'] = [{'Type': 'Men'}, {'Parameter': '1000'}];
There is a good way, but I do not know if it is what you want.
I am using a JSON structure to store details of a person. Basically name, phone, registeredTimestamp etc., will be other attributes, and Primary key will be the email address.
markedLocations, visitedLocations, searchHistory and recommendation are the lists or Map as AWS calls it. It will contain many JSON objects.
JSON Structure-
{
"name":"Mama Miya",
"phone":"9383883223",
"registeredTimestamp":"some-time",
"lastActiveTimestamp":"some-time",
"signinType":"facebook",
"additionalSigninData":{
"key1":"value1",
"key2":"value2"
},
"markedLocations":[
{
"latitude":"77.33",
"longitude":"12.33",
"name":"Home",
"description":"my new home",
"placeid":"55334433",
"image":"url/abc.png"
}
]
}
From the app, if the user visits a new location, I need to add a new JSON Object to the markedLocations.
So the markedLocations should look something like-
"markedLocations":[
{
"latitude":"77.33",
"longitude":"12.33",
"name":"Home",
"description":"my new home",
"placeid":"55334433",
"image":"url/abc.png"
},{
"latitude":"22.11",
"longitude":"22.55",
"name":"Ocean",
"description":"Ocean",
"placeid":"32423423",
"image":"url/icean.png"
}
]
Code/Schema-
var item = {
'email': {'S': req.body.email},
'phone': {'S': req.body.phone},
'registeredTimestamp': {'S': req.body.registeredTimestamp},
'lastActiveTimestamp': {'S': req.body.lastActiveTimestamp},
'signinType': {'S': req.body.signinType},
'version': {'S': req.body.version},
'markedLocations': {'L': req.body.markedLocations}
};
I checked -
In DynamoDB how do I append an element to a list field using Java link
updating a JSON array in AWS dynamoDB link
Updating a Set in Dynamo db using Node Js link
how to update item in dynamoDB using nodejs? link
And checked AWS docs for UpdateItem API. I didn't find anything relevant to my problem/doubt.
Please can you tell me if there is a way to append the JSON array with a new JSON object in NodeJS? I am not able proceed on how to implement the same.
OR
Should I create separate table for each Array and have email as primary key and timestamp as sort key and proceed?
PS: I am new to DynamoDB, I've worked with MongoDB earlier and there are ways to work with JSON arrays and objects there. Unable to find a way here.
Use list_append() and if_not_exists() together in an UpdateExpression to append to a potentially non-existent list column:
var AWS = require('aws-sdk')
var DB = new AWS.DynamoDB.DocumentClient()
function appendMarkedLocation (personId, location) {
return DB.update({
TableName: 'people',
Key: { id: personId },
ReturnValues: 'ALL_NEW',
UpdateExpression: 'set #markedLocations = list_append(if_not_exists(#markedLocations, :empty_list), :location)',
ExpressionAttributeNames: {
'#markedLocations': 'markedLocations'
},
ExpressionAttributeValues: {
':location': [location],
':empty_list': []
}
}).promise()
}
appendMarkedLocation('somePeronId', {
latitude: '22.11',
longitude: '22.55',
name: 'Ocean',
description: 'Ocean',
placeid: '32423423',
image: 'url/icean.png'
}).then(console.log)