簡體   English   中英

通過循環使用jQuery創建和填充JSON對象

[英]Creating and Populating JSON Object with jQuery via Loops

我正在嘗試使用多個.each()循環動態創建JSON對象。 我嘗試使用.push(),但是我只能獲得填充的JSON對象的第一個“層”(第一個數組)。

JS通過Excel電子表格(2003 / XML)文件進行解析,並且需要輸出此JSON對象“樣式”,因此我可以使用它在頁面上生成CSS。 因此,基本上,我們保存了一個Excel XML Spreadsheet,我的JS使用AJAX來“獲取”它,然后解析它以提取樣式(以及工作表/其數據)。 然后,提取過程應“動態”創建此JSON對象,以在JS文件中的其他位置使用。

這是在完成各種功能和循環之后我需要的JSON(除非有更好的結構或對我的情況更有意義的結構)...

var styles = [
  "Default": {
    "Name": "Normal",
    "Style": {
      "Alignment": {
        "Vertical": "Bottom"
      },
      "Font": {
        "Name": "Calibri",
        "Family": "Swiss",
        "Size": "11",
        "Color": "#000000"
      }
    }
  },
  "s57": {
    "Name": "Hyperlink",
    "Style": {
      "Font": {
        "Name": "Calibri",
        "Family": "Swiss",
        "Size": "11",
        "Color": "#0066CC",
        "Underline": "Single"
      }
    }
  }
]

MY JS(到目前為止)

var styles = []

$(xml).find('Style').each(function(){

  var style = {}

  var id = $(this).attr('ss:ID');

  var type = $(this).children();

  type.each(function() {

    $.each(this.attributes, function() {

      if (this.specified) {
        style[this.name] = this.value;
      }

    });

  });

  styles.push(style);

  console.log(styles);

});

效果不是很好。 一旦添加了style[this.name] = this.value ,控制台就會顯示一堆“ X:Object”條目。

那么,如何使用上面的.each()和$ .each()循環“動態”生成JSON對象?

提前致謝!

PS我已經搜索了很多,以試圖找到答案。 我已經找到了如何做一些零碎的東西,但是沒有一個能智能地填充對象...

編輯:

這是我正在“解析”的XML文件:

.XML受害者

更新:

我越來越近:

// Create JSON Object "styles"
var styles = [];

$(xml).find('Style').each(function(){

  var style = {};

  var id = $(this).attr('ss:ID');
  var type = $(this).children();

  type.each(function() {

    $.each(this.attributes, function() {

      if (this.specified) {
        style[this.name] = this.value;
      }

    });

  });

  //styles[id] = style;
  styles.push(style);

});

console.log(styles);

$(document).ready(function(){
  $('body').append('<div class="json-output"/>');
  $('.json-output').append(JSON.stringify(styles));
});

** JSON.stringify(styles)現在通過上述腳本輸出

[
{
"ss:Vertical":"Bottom",
"ss:FontName":"Calibri",
"x:Family":"Swiss",
"ss:Size":"11",
"ss:Color":"#000000"
},
"ss:FontName":"Calibri",
"x:Family":"Swiss",
"ss:Size":"11",
"ss:Color":"#0066CC",
"ss:Underline":"Single"
},
{
"ss:Horizontal":"Left",
"ss:Vertical":"Center",
"ss:Indent":"1"
},    {
"ss:Vertical":"Center",
"ss:WrapText":"1",
"ss:FontName":"Calibri",
"x:Family":"Swiss",
"ss:Size":"11",
"ss:Color":"#000000",
"ss:Bold":"1"
},
{
"ss:Vertical":"Center",
"ss:WrapText":"1",
"ss:FontName":"Calibri",
"x:Family":"Swiss",
"ss:Size":"11",
"ss:Color":"#008000",
"ss:Bold":"1"
},
{
"ss:Vertical":"Center",
"ss:WrapText":"1"
},
{
"ss:Vertical":"Center",
"ss:WrapText":"1",
"ss:FontName":"Calibri",
"x:Family":"Swiss",
"ss:Size":"11",
"ss:Color":"#808080",
"ss:Bold":"1",
"ss:Pattern":"Solid"
},
{
"ss:Horizontal":"Left",
"ss:Vertical":"Bottom"
},
{
"ss:Horizontal":"Left",
"ss:Vertical":"Center",
"ss:WrapText":"1",
"ss:Format":"0"
},
{
"ss:Horizontal":"Left",
"ss:Vertical":"Center",
"ss:Indent":"1",
"ss:WrapText":"1"
}
]
...

您需要的是

  var root = $(xml),
      styles = {},
      all = root.find('Style');

  all.each(function(index, item){
    var self = $(this),
        id = self.attr('ss:ID'),
        type = self.children(),
        style = {};

    styles[id] = style;

    type.each(function(index, item){
      var attributes = item.attributes;
      if (attributes.length){
        style[ item.nodeName ] = {};
        for (var i = 0, l = attributes.length; i < l; i++){
          var attribute = attributes[i],
              attrName = attribute.nodeName;

          if (attrName.indexOf(':') > -1){
            attrName = attrName.split(':')[1];
          }
          style[ item.nodeName ][ attrName ] = attribute.value;
        }
      }
    });
  });

它將返回您所描述的對象( 盡管正確,因為目標變量是錯誤的,因為它是一個數組,但是具有對象的結構

感謝您發布XML文件。 代替使用this.name,而是引用this.localName可以獲取非XML名稱空間的名稱-實際的節點名稱。 這將返回一個具有在其中定義的樣式的Objects數組。 此外,由於您使用的是數組,因此無法設置樣式的名稱/ ID。 您需要將“樣式”更改為對象,並且可以使用與每種樣式相同的方式來設置名稱/ ID。

編輯更新了我的完整代碼,因為我遺漏了一些可能確實對您有幫助的東西。

嘗試:

$(function () {
    $.get('/StackTest.xml', function (xml) {  // i had it locally saved in my sandbox
        var styles = {};

        $(xml).find('Style').each(function () {
            var style = {};
            var id = $(this).attr('ss:ID');
            var type = $(this).children();

            type.each(function () {
                $.each(this.attributes, function () {
                    if (this.specified) {
                        style[this.localName] = this.value;
                    }
                });
            });
            styles[id] = style;
        });
        console.log(styles);
        console.log(JSON.stringify(styles)); // see what it looks like as string - notice no array.
    });
});

所以這就是我最終得到的...

它允許我引用諸如styles['s57'].FontName (例如,所有具有s57樣式的單元格的字體)

// Get Excel Spreadsheet (2003/XML Only!)
$.ajax({
  type: "GET",
  url: '/data/KH-3140300109.xml',
  dataType: "xml",
  success: function(xml) {
    console.log('%cgetExcel() was successful!', 'color:green; font-weight:bold;');
    createStyles(xml);
  },
  error: function(){
    console.error('getData() was unsuccessful');
  }
});

function createStyles(xml) {

  // Create JSON object "styles"
  var styles = {}

  $(xml).find('Style').each(function(){

    var id = $(this).attr('ss:ID');
    var name = $(this).attr('ss:Name');
    var type = $(this).children();

    // Create JSON object "style"
    var style = {};

    // Identify the style
    styles[id] = style;

    // Log its name
    style['Name'] = name;

    // Add various styles to that style
    type.each(function() {

      // Loop through each style-type and log it's values
      $.each(this.attributes, function() {

        // If it exists... Log it!
        if (this.specified) {
          style[stripPrefix(this.name)] = this.value;
        }

      });

    });;

  });

  console.log('Moment of truth... ' + styles['s57'].FontName);

  $(document).ready(function(){
    $('body').append('<div class="json-output"/>');
    $('.json-output').append(JSON.stringify(styles));
  });

}

這是它的輸出(JSON-或其他形式...)

{
  "Default":{
    "Name":"Normal",
    "Vertical":"Bottom",
    "FontName":"Calibri",
    "Family":"Swiss",
    "Size":"11",
    "Color":"#000000"
  },
  "s57":{
    "Name":"Hyperlink",
    "FontName":"Calibri",
    "Family":"Swiss",
    "Size":"11",
    "Color":"#0066CC",
    "Underline":"Single"
  },
  "s58":{
    "Horizontal":"Left",
    "Vertical":"Center",
    "Indent":"1"
  }
  ...
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM