-1

我的代码如下

 'use strict';

var connectionString = process.argv[2];

var Mqtt = require('azure-iot-device-mqtt').Mqtt;
var Client = require('azure-iot-device').Client;
var Message = require('azure-iot-device').Message;

var client = Client.fromConnectionString(connectionString, Mqtt);

// Timeout created by setInterval
var intervalLoop = null;

const chalk = require('chalk');

client.open(function(err){
    if(err){
        console.log(chalk.red('Could not connect: ' + err.toString()));
    }else{
        console.log(chalk.blue('Client connected'));
    }
});

// Function to handle the SetTelemetryInterval direct method call from IoT hub
function onSetTelemetryInterval(request, response) {
  // Function to send a direct method reponse to your IoT hub.
  function directMethodResponse(err) {
    if(err) {
      console.error(chalk.red('An error ocurred when sending a method response:\n' + err.toString()));
    } else {
        console.log(chalk.green('Response to method \'' + request.methodName + '\' sent successfully.' ));
    }
  }

  console.log(chalk.green('Direct method payload received:'));
  console.log(chalk.green(request.payload));

  // Check that a numeric value was passed as a parameter
  if (isNaN(request.payload)) {
    console.log(chalk.red('Invalid interval response received in payload'));
    // Report failure back to your hub.
    response.send(400, 'Invalid direct method parameter: ' + request.payload, directMethodResponse);

  } else {

    // Reset the interval timer
    clearInterval(intervalLoop);
    intervalLoop = setInterval(sendMessage, request.payload * 1000);

    // Report success back to your hub.
    response.send(200, 'Telemetry interval set: ' + request.payload, directMethodResponse);
  }
}

function sendMessage(){

    //message standard
    var serviceId = 1
    var serviceName = "ParkingService"
    var deviceId = 1
    var deviceName = "TestDevice1"
    var date = Date.now();

    // contents
    var temperature = 20 + (Math.random() * 15);
    var humidity = 60 + (Math.random() * 20);
    var illuminance = 100;
    var contents = JSON.stringify(
                             {
                                 temperature: temperature,
                                 humidity: humidity,
                                 illuminance: illuminance
                             }
                         );

    var data = JSON.stringify(
        {
            serviceId: serviceId,
            serviceName: serviceName,
            deviceId: deviceId,
            deviceName: deviceName,
            date: date,
            contents: contents
        }
    );

    var message = new Message(data);
    client.sendEvent(message, function(err){
        if(err){
            console.error('send error:' + err.toString());
        }else{
            console.log('message sent' + message.getData());
        }
    });
}

// Set up the handler for the SetTelemetryInterval direct method call.
client.onDeviceMethod('SetTelemetryInterval', onSetTelemetryInterval);

// Create a message and send it to the IoT hub, initially every second.
intervalLoop = setInterval(sendMessage, 1000*60);

我想得到这样的 JSON

{"serviceId":1,
"serviceName":"TestService",
"deviceId":1,
"deviceName":"TestDevice1",
"date":1552981083556,
"contents": 
         {
          "temperature":34.99911143581406,
          "humidity":78.4002692509342,
          "illuminance":100
         }
}

但是结果和我预想的不一样。我认为内容看起来像一个字符串而不是对象。

{"serviceId":1,
"serviceName":"TestService",
"deviceId":1,
"deviceName":"TestDevice1",
"date":1552981083556,"contents":"{\"temperature\":34.99911143581406,\"humidity\":78.4002692509342,\"illuminance\":100}"}

因此 Azure Cosmos DB 和 IoT Hub 无法识别 contents.temperature。serviceId 识别成功。

如何创建包含嵌套对象的 JSON?

==================================================== =============

在我修改了那个代码之后,它工作得很好!(IoT 中心路由和 Cosmos DB)

没有问题。

var contents = 
                                 {
                                     temperature: temperature,
                                     humidity: humidity,
                                     illuminance: illuminance
                                 }
                             ;

        var data = JSON.stringify(
            {
                serviceId: serviceId,
                serviceName: serviceName,
                deviceId: deviceId,
                deviceName: deviceName,
                date: date,
                contents: contents
            }
        );
4

1 回答 1

1

JSON.stringify返回一个字符串。https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

你应该使用JSON.parse https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse

于 2019-03-19T07:53:12.873 回答