2017-06-29 3 views
1

Ich verwende jQuery, um verschachtelte Listen als JSON auszugeben.Verschachtelte Listen als strukturierte JSON schreiben

Ich habe Probleme mit den verschachtelten Elementen. Ich habe ein Plunk erstellt, mit dem Sie das Problem mit einem einfachen Klick auf eine Schaltfläche neu erstellen können.

Plunk: https://plnkr.co/edit/jLi9epblNAtMbzezcRSY?p=preview

HTML:

<h1>Hello Plunker!</h1> 
<div class="dd" name="agenda-nestable" id="nestable"> 
    <ol id="agenda-root" class="dd-list"> 
      <li class="dd-item" data-id="0" id="0"> 
       <div class="dd-handle">Pledge of Allegiance</div> 
      </li> 
      <li class="dd-item" data-id="0" id="0"> 
       <div class="dd-handle">Roll Call</div> 
        <ol class="dd-list"> 
          <li class="dd-item" data-id="0"> 
          <div class="dd-handle">Establish a Quorum</div></li> 
        </ol> 
      </li> 
      <li class="dd-item" data-id="0" id="0"> 
       <div class="dd-handle">Public Comment</div> 
        <ol class="dd-list"> 
          <li class="dd-item" data-id="0"> 
          <div class="dd-handle">Address</div></li> 
          <li class="dd-item" data-id="0"> 
          <div class="dd-handle">Open Floor</div></li> 
        </ol> 
      </li> 
      <li class="dd-item" data-id="0" id="0"> 
       <div class="dd-handle">Action to set agenda and to approve consent agenda items</div> 
      </li> 
      <li class="dd-item" data-id="0" id="0"> 
       <div class="dd-handle">Presentations and awards</div> 
      </li> 
      <li class="dd-item" data-id="0" id="0"> 
       <div class="dd-handle">Matters set for a specific time</div> 
      </li> 
      <li class="dd-item" data-id="0" id="0"> 
       <div class="dd-handle">Regular Agenda</div> 
      </li> 
      <li class="dd-item" data-id="0" id="0"> 
       <div class="dd-handle">Governing Board</div> 
      </li> 
      <li class="dd-item" data-id="0" id="0"> 
       <div class="dd-handle">Closed Session</div> 
      </li> 
    </ol> 
</div> 
<pre id="jsonOutput"></pre> 
<button value onclick='convertToJson()'>Convert nodes to JSON</button> 

Code:

function convertToJson() { 
    var sectionOrder = ""; 
    var itemOrder = ""; 
    var sectionDelimiter = ""; 
    var itemDelimiter = ""; 

    var agendaDiv = $("[name='agenda-nestable']"); 
    var agendaSections = $(agendaDiv).find("ol#agenda-root>li"); 
    var sections = []; 

    for (var i = 0; i < agendaSections.length; i++) { 
     var agendaSection = agendaSections[i]; 
     var section = {}; 
     section.Id = $(agendaSection).attr('data-id'); 
     section.SectionText = $(agendaSection).find("div:first-child").text(); // Something wrong here 
     section.Items = []; 

     var sectionItems = $(section).find("ol>li"); 
     for (var j = 0; j < sectionItems.length; j++) { 
      var sectionItem = sectionItems[j]; 
      var item = {}; 
      item.Id = $(sectionItem).attr('data-id'); 
      item.ItemText = $(sectionItem).find("div:first-child").text(); // Something wrong here 
      section.Items.push(item); 
     } 
     sections.push(section); 
    } 
    var json = JSON.stringify(sections, null, 2);; 
    $('#jsonOutput').text(json); 
    console.log(json); 
    return json; 
} 

Ausgang:

{ 
    "Id": "0", 
    "SectionText": "Pledge of Allegiance", 
    "Items": [] 
    }, 
    { 
    "Id": "0", 
    "SectionText": "Roll CallEstablish a Quorum", // THIS IS WRONG, should be in Items Array, not munged together 
    "Items": [] 
    }, 
    { 
    "Id": "0", 
    "SectionText": "Public CommentAddressOpen Floor", // THIS IS WRONG, should be in Items Array, not munged together 
    "Items": [] 
    }, 
    { 
    "Id": "0", 
    "SectionText": "Action to set agenda and to approve consent agenda items", 
    "Items": [] 
    }, 
    { 
    "Id": "0", 
    "SectionText": "Presentations and awards", 
    "Items": [] 
    }, 
    { 
    "Id": "0", 
    "SectionText": "Matters set for a specific time", 
    "Items": [] 
    }, 
    { 
    "Id": "0", 
    "SectionText": "Regular Agenda", 
    "Items": [] 
    }, 
    { 
    "Id": "0", 
    "SectionText": "Governing Board", 
    "Items": [] 
    }, 
    { 
    "Id": "0", 
    "SectionText": "Closed Session", 
    "Items": [] 
    } 
] 

Vielen Dank für einen Blick, ich schätze es wirklich !!!

Philip

+0

"Ich habe Probleme". Was sind die Probleme? Der Code im Link scheint nicht der gleiche zu sein wie in der Frage – ADyson

Antwort

1

var section = {};

var sectionItems = $ (Abschnitt) .find ("ol> li");

Dies ist Ihr Problem. Sie versuchen, das Objekt als jquery-Element zu verwenden.

Verwenden Sie stattdessen $ (agendaSection).

Auch Ihre Li-Elemente haben die gleiche ID, die nicht erlaubt ist.

$(document).ready(function() { 
 

 
    function convertToJson() { 
 

 
    var nestable = $("#nestable"), 
 
     root = $('#agenda-root'), 
 
     agendaSections = $("#agenda-root>li"), 
 
     sections = []; 
 
    
 
    agendaSections.each(function() { 
 
     var section = {}; 
 
     section.Id = $(this).attr('data-id'); 
 
     section.SectionText = $(this).find(".dd-handle").first().text(); // Something wrong here 
 
     section.Items = []; 
 
     
 
     $(this).find('.dd-list').find('.dd-item').each(function() { 
 
     var item = {}; 
 
     item.Id = $(this).attr('data-id'); 
 
     item.ItemText = $(this).find(".dd-handle").first().text(); // Something wrong here 
 
     section.Items.push(item); 
 
     }) 
 
     sections.push(section); 
 
    }); 
 
    
 
    var json = JSON.stringify(sections, null, 2); 
 
    $('#jsonOutput').text(json); 
 
    console.log(json); 
 
    return json; 
 
    } 
 

 
    $('#toJson').click(convertToJson); 
 

 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div class="dd" name="agenda-nestable" id="nestable"> 
 
    <ol id="agenda-root" class="dd-list"> 
 
     <li class="dd-item" data-id="1" id="1"> 
 
     <div class="dd-handle">Pledge of Allegiance</div> 
 
     </li> 
 
     <li class="dd-item" data-id="2" id="2"> 
 
     <div class="dd-handle">Roll Call</div> 
 
     <ol class="dd-list"> 
 
      <li class="dd-item" data-id="1"> 
 
      <div class="dd-handle">Establish a Quorum</div> 
 
      </li> 
 
     </ol> 
 
     </li> 
 
     <li class="dd-item" data-id="3" id="3"> 
 
     <div class="dd-handle">Public Comment</div> 
 
     <ol class="dd-list"> 
 
      <li class="dd-item" data-id="1"> 
 
      <div class="dd-handle">Address</div> 
 
      </li> 
 
      <li class="dd-item" data-id="2"> 
 
      <div class="dd-handle">Open Floor</div> 
 
      </li> 
 
     </ol> 
 
     </li> 
 
     <li class="dd-item" data-id="4" id="4"> 
 
     <div class="dd-handle">Action to set agenda and to approve consent agenda items</div> 
 
     </li> 
 
     <li class="dd-item" data-id="5" id="5"> 
 
     <div class="dd-handle">Presentations and awards</div> 
 
     </li> 
 
     <li class="dd-item" data-id="6" id="6"> 
 
     <div class="dd-handle">Matters set for a specific time</div> 
 
     </li> 
 
     <li class="dd-item" data-id="7" id="7"> 
 
     <div class="dd-handle">Regular Agenda</div> 
 
     </li> 
 
     <li class="dd-item" data-id="8" id="8"> 
 
     <div class="dd-handle">Governing Board</div> 
 
     </li> 
 
     <li class="dd-item" data-id="9" id="9"> 
 
     <div class="dd-handle">Closed Session</div> 
 
     </li> 
 
    </ol> 
 
    </div> 
 

 
    <pre id="jsonOutput"></pre> 
 
    <button type="button" id="toJson">Convert nodes to JSON</button>

Dies ist, wie es funktioniert.

+0

Das ist unglaublich, und Ihr Code ist sehr sauber. Ich danke dir sehr! –

1

Es gibt zwei Probleme in Ihrem JS.

Ausgabe: 1

find ("div: first-child") werden alle div entsprechen: first-Kind, das ist, warum der Text des div unter ol> li auch erfasst wird. So ändern Sie die Zeile

von

$(agendaSection).find("div:first-child").text(); 

zu

$(agendaSection).find("> div:first-child").text(); 

Ausgabe: 2

Sie müssen agendaSection passiert, wenn das ol zu finden, nicht Abschnitt, der eine Variable, die hält ein Objekt.

var sectionItems = $(agendaSection).find("ol>li"); 
1

Ausgabe 1: Text zusammen munged ist:

JQuery .text() gibt den Textinhalt des Kindes alle Knoten unter dem Quellknoten. Deshalb bekommst du "Public CommentAddressOpen Floor". http://api.jquery.com/text/

Finden Sie diese Antwort für einige Möglichkeiten, um dieses Problem zu vermeiden: jQuery: exclude children from .text(). Die definitive Möglichkeit, dieses Problem zu vermeiden, finden Sie hier: http://viralpatel.net/blogs/jquery-get-text-element-without-child-element/.

Ausgabe 2: Warum keine Artikel?

Sobald das behoben ist, haben Sie noch keine Unterpunkte. Hier ist ein guter Tipp: Wenn Ihre Ausgabe nicht Ihren Erwartungen entspricht, überprüfen Sie Ihre Eingabe. In diesem Fall ist Ihr Selektor falsch. Sie wählen aus Ihrem Ausgabearray statt Ihrer Liste von jQuery-Abschnitten. Mit anderen Worten, dies:

agendaSection.find("ol>li"); 

hier ein Stift ist, das funktioniert:

$(section).find("ol>li"); 

dies sein sollte

https://codepen.io/anon/pen/awqwEV

Im Stift, nahm ich auch die Freiheit von prefixing die jQuery-Variablen mit $ und die jQuery-Zuweisung bei der Variablenzuweisung. So ist agendaSection jetzt $ agendaSection, und jQuery erledigt nur die Arbeit, dieses Element einmal zu umbrechen. Dies sind gute Praktiken, die Ihnen auf lange Sicht helfen sollten.

Verwandte Themen