如何使用JSON嵌入嵌套响应?

时间:2014-02-25 07:36:35

标签: json node.js

我想使用JSON发送以下响应消息。怎么做到这一点?我是否需要定义嵌套对象?

示例:

{
Name: "Employee name" 
responseStatus { 
  "status":{
  "statuscode":"200",
  "statusmessage":"Success"
  }
},

 "Department":{
  "DepartmentName":"Name",
  "info":[
  {
  "code":"400",
  "status":"valid",
  "DepartmentData":[
  {
  "key":"key",
  "value":"value"
  },  
  {
  "key":"key1"
   value:"value1"
  },
  {
   key :"key2"
   value : "value2"
  }
  ]
  ... some other info..
 } 
}
....

1 个答案:

答案 0 :(得分:1)

是的,的确如此。例如:

var obj = {};
obj.Name = "Employee name";
obj.responseStatus = { 
  status: {
    statuscode: "200",
    statusmessage: "Success"
  }
};
obj.Department = {
  DepartmentName: "Name",
  info: []
};
obj.Department.info.push({
  code: "400",
  status: "valid",
  etc: true
});

res.end(JSON.stringify(obj));

使用jsonlint

验证原始帖子
{
    "Name": "Employee name",
    "responseStatus": {
        "status": {
            "statuscode": "200",
            "statusmessage": "Success"
        }
    },
    "Department": {
        "DepartmentName": "Name",
        "info": [
            {
                "code": "400",
                "status": "valid",
                "DepartmentData": [
                    {
                        "key": "key",
                        "value": "value"
                    },
                    {
                        "key": "key1",
                        "value": "value1"
                    },
                    {
                        "key": "key2",
                        "value": "value2"
                    }
                ]
            }
        ]
    }
}