Javascript 我想创建一个JSON字符串,其中包含Azure IoT Hub或Cosmos的嵌套对象

Javascript 我想创建一个JSON字符串,其中包含Azure IoT Hub或Cosmos的嵌套对象,javascript,node.js,json,azure-cosmosdb,stringify,Javascript,Node.js,Json,Azure Cosmosdb,Stringify,我的代码在下面 '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.fromConnection

我的代码在下面

 '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和物联网中心无法识别 内容物。温度。 已成功识别serviceId

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

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

在我修改了代码之后,它工作得很好! (物联网枢纽路由和宇宙数据库)

没有问题

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

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

JSON.stringify
返回一个字符串


您应该使用
JSON.parse

该代码不会创建JSON字符串。您显示的JSON字符串确实有一个用于
内容的字符串,而不是一个对象,但您的代码肯定没有这样做。真正的代码必须在
contents
上执行
JSON.stringify
,然后才能将其添加到您正在执行的
stringify
操作的对象中。解决方案不是这样做,而是像问题中的代码那样去做。^^投票决定以后以打字错误/不重复/对其他人不有用的方式结束。你不能这样做,因为“内容”是json对象,必须转义,因为字符串中的字符串将被转义。@KumarLachhani-当然可以。JSON允许嵌套结构——OP问题中的代码成功地创建了嵌套结构。@KumarLachhani——问题中所示,几乎没有理由在另一个JSON字符串中包含JSON字符串(事实上,问题中的结构就是OP所问的问题)。遗憾的是,这个问题没有意义(显示代码做了一件事,JSON是由其他事情产生的),现在OP说问题已经解决了,与JSON无关。所以……这里没什么可看的。:-)欢迎来到堆栈溢出!你想帮忙真是太好了。请拿着(你得到了一个徽章!),四处看看,然后通读下面的内容。在发布答案之前,请务必仔细阅读问题。很明显,OP(“原始海报”——提问者)知道
JSON.stringify
创建一个字符串,而这正是他们想要做的,不解析字符串。OP在使用JSON.stringify将对象转换为字符串后尝试访问该对象,因此我不确定海报是否了解JSON.parse。我认为这只是一次普通的帮助他人的尝试。@NikNik这正是我发布这篇文章的原因,我引用了文档,以确保海报能够理解JSON.stringify的功能(返回字符串)@T.J.Crowder是的,我读过这篇文章,我想我知道如何发布,因为我引用了文档,而不仅仅是说:“使用这个或使用那个”,当某人试图创建JSON字符串时,告诉他们使用
JSON.parse
是没有意义的。如果仔细阅读问题,他们显然A)不需要
JSON.parse
,B)已经正确创建了字符串。