简体   繁体   中英

Dealing with JSON data returned from a DynamoDB query

I am storing data in a DynamoDb table. I have 3 columns:

hub_id (edit: primary partition key)

on_time (sort key - this is a date time stored as a string)

details this contains my JSON data (information from a sensor):

{ "hub_id" : { "S" : "PnKVrm12" }, "temperature" : { "S" : "23" }, "sensor_name" : { "S" : "Tech Lab" }}

Using react-native and aws amplify I can query the table using the following code and return the correct number of rows :

  // setup query params
var params = {
TableName : "hiddenprojectv-mobilehub-1542262168-hidden",
ProjectionExpression:"hub_id, details.temperature, details.sensor_name",
KeyConditionExpression: "hub_id = :hid",
ExpressionAttributeValues: {
    ":hid":"PnKVrm12"
    }
};


//execute query using params
db.query(params, function(err, data) {
if (err) {
    console.log("Unable to query. Error:", JSON.stringify(err, null, 2));
} else {
    console.log("Query succeeded.");
    data.Items.forEach(function(details) {
        console.log(details.hub_id,details.sensor_name); 

    });
}
});

but I am struggling to get at the data held in the Json object (details column). The query above returns:

16:44:45: PnKVrm12 undefined

I expected it to return:

16:44:45: PnKVrm12 Tech Lab

for some reason I can never access data in either temperature or sensor_name.

I would appreciate some advice if you have time.

Your ProjectionExpression is accessed in your forEach loop and provides:

details = { hub_id: 'x', details: { temperature: 'x', sensor_name: 'x' } };

You are not using your data structure properly. To access the sensor_name property you must use:

`details.details.sensor_name'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM