javascript将JSON字符串转换为JSON对象

时间:2015-10-15 11:09:45

标签: javascript json

我使用javascript并循环遍历提交表​​单的值,并尝试从表单值中构建一个子对象。

这是我需要的最终对象的一个​​例子:

{
  "DataObject": {
    "user": { "-name": "username" },
    "contentFile": {
      "-filename": "Breaking_News",
      "lock": { "-fileIsBeingEdited": "false" },
      "content": {
        "line": [
          {
            "-index": "1",
            "-text": "this is the header"
          },
          {
            "-index": "2",
            "-text": "this is the first line"
          },
          {
            "-index": "3",
            "-text": "this is the second line"
          }
        ]
      }
    }
  }
}

到目前为止,我将所有这些数据添加到字符串中,因为这似乎是我可以将表单值(行数组)插入对象中间的唯一方法。

var jsonStr = '{'
       + 'iceteaDataObject: {'
        + 'user: {"-name": "hindsc52"},'
          + 'contentFile: {'
          + '"-filename": "Ticker",'
          + 'lock: { "-fileIsBeingEdited": "false" },'
          + 'content: {'
          +  'line: ['

    for(var i = 0; i < elem.length; i++) {
      if(!elem[i].value == '') {
        jsonStr += '{'
        jsonStr += "-index: " + i + ',';
        jsonStr += "-text: " + elem[i].value;
        jsonStr += '},'
      }
    }

    jsonStr += ']}}}}';

    console.log(JSON.parse(jsonData));

但是在运行时我收到错误:意外令牌'我'。

我尝试过使用stringily,但之后再次输出整个刺痛。

4 个答案:

答案 0 :(得分:1)

您不需要或想要JSON,只需构建对象:

// Sample data
var elem = [{
  value: "one"
}, {
  value: "two"
}];

// Build the object
var obj = {
  "DataObject": {
    "user": {
      "-name": "username"
    },
    "contentFile": {
      "-filename": "Breaking_News",
      "lock": {
        "-fileIsBeingEdited": "false"
      },
      "content": {
        "line": []
      }
    }
  }
};
var line = obj.DataObject.contentFile.content.line;
elem.forEach(function(entry, index) {
  if (entry.value != '') {
    line.push({
      "-index": index,
      "-text": entry.value
    });
  }
});

// Show result:
document.body.innerHTML =
  "<pre>" +
  JSON.stringify(obj, null, 2) +
  "</pre>";

附注:你没有检查这样的空白字符串:

if (!entry.value == '') { // <== Incorrect

您可以使用:

if (entry.value != '') {

或:

if (entry.value) {

答案 1 :(得分:0)

您不应该像这样构建JSON,而是使用JSON.stringify()(请参阅MDN doc):

var myObject={foo:"bar"};
var myJSON=JSON.stringify(myObject);
console.log(myJSON); //echo {"foo":"bar"}

答案 2 :(得分:0)

这是另一种方式:

var json = {
  iceteaDataObject: {
    "-name": "hindsc52"
  },
  contentFile: {
    "-filename": "Ticker",
    lock: { "-fileIsBeingEdited": "false" },
    content: {line: []}
  }
}
for(var i = 0; i < elem.length; i++) {
      if(!elem[i].value == '') {
        json.contentFile.content.line.push({"-index": i,"-text": elem[i].value }
      }
    }
var jsonStr = JSON.stringify(json);

答案 3 :(得分:0)

您需要将所有密钥都放在引号中才能生效。正如其他人所指出的那样,你并不是真的应该这样做。

如果您仍想按照自己的方式行事,请尝试以下方法:

var jsonStr = '{'
      + '"iceteaDataObject": {'
      + '"user": {"-name": "hindsc52"},'
      + '"contentFile": {'
      + '"-filename": "Ticker",'
      + '"lock": { "-fileIsBeingEdited": "false" },'
      + '"content": {'
      +  '"line": ['

for(var i = 0; i < elem.length; i++) {
  if(!elem[i].value == '') {
    jsonStr += '{'
    jsonStr += '"-index": ' + i + ',';
    jsonStr += '"-text": ' + '"' + elem[i].value + '"';
    jsonStr += '},'
  }
}

jsonStr += ']}}}}';