簡體   English   中英

javascript將JSON字符串轉換為JSON對象

[英]javascript convert JSON string to JSON object

我一直在使用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));

但是,運行此命令時出現錯誤:意外令牌'i'。

我試圖嚴格使用,但是只是再次輸出整個刺。

您不需要或不需要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) {

您不應像這樣構建JSON,而應使用JSON.stringify() (請參見MDN doc ):

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

這是另一種方法:

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

您需要將所有鍵都放在引號中才能起作用。 正如其他人指出的那樣,您實際上不應該這樣做。

如果您仍然想按照自己的方式做,請嘗試以下操作:

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