简体   繁体   English

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

[英]javascript convert JSON string to JSON object

I al using javascript and looping through the values of a submitted form and trying to build a son object out of the form values. 我一直在使用javascript并遍历提交表​​单的值,并尝试从表单值中构建子对象。

This is an example of the final object I need: 这是我需要的最终对象的一个​​示例:

{
  "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"
          }
        ]
      }
    }
  }
}

So far i am adding all of this data to a string as that seems to be the only way i can insert the form values (the line array) into the middle of the object. 到目前为止,我将所有这些数据添加到字符串中,因为这似乎是将表单值(行数组)插入对象中间的唯一方法。

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));

however when running this I get the error: unexpected token 'i'. 但是,运行此命令时出现错误:意外令牌'i'。

I have tried to use stringily but then just outputs the entire sting again. 我试图严格使用,但是只是再次输出整个刺。

You don't need or want JSON for this, just build the object: 您不需要或不需要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>"; 


Side note: You don't check for blank strings like this: 旁注:您不会像这样检查空白字符串:

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

You can use: 您可以使用:

if (entry.value != '') {

or: 要么:

if (entry.value) {

You shouldn't build JSON like this, but use JSON.stringify() (see MDN doc ) instead: 您不应像这样构建JSON,而应使用JSON.stringify() (请参见MDN doc ):

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

Here is an alternative way: 这是另一种方法:

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);

You need to put all your keys in quotes for this to work. 您需要将所有键都放在引号中才能起作用。 As the others have pointed out though, you are not really supposed to do this. 正如其他人指出的那样,您实际上不应该这样做。

If you still want to do it your way, try this: 如果您仍然想按照自己的方式做,请尝试以下操作:

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 += ']}}}}';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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