how to convert json to array in javascript for an li list

Blue Moose

I have a JSON string the is pulled and returns the following.

var result = {
  "0": { NAME: "NONE" },
  "1": { NAME: "REGISTRATION" },
  "2": { NAME: "PAPER" },
  "3": { NAME: "BLACK" },
  "4": { NAME: "C=100M=0Y=0K=0" },
  "5": { NAME: "C=0M=100Y=0K=0" },
  "6": { NAME: "C=0M=0Y=100K=0" },
  "7": { NAME: "C=15M=100Y=100K=0" },
  "8": { NAME: "C=75M=5Y=100K=0" },
  "9": { NAME: "C=100M=90Y=10K=0" }
};

These are colors from an InDesign document. I am trying to convert to a string in javascript and everything I have tried is not working.

the closest I have gotten is the following

var result = {
  "0": { NAME: "NONE" },
  "1": { NAME: "REGISTRATION" },
  "2": { NAME: "PAPER" },
  "3": { NAME: "BLACK" },
  "4": { NAME: "C=100M=0Y=0K=0" },
  "5": { NAME: "C=0M=100Y=0K=0" },
  "6": { NAME: "C=0M=0Y=100K=0" },
  "7": { NAME: "C=15M=100Y=100K=0" },
  "8": { NAME: "C=75M=5Y=100K=0" },
  "9": { NAME: "C=100M=90Y=10K=0" }
};

var listEl = document.getElementById('swatches');
    makeList(result,listEl);

function makeList(jsonObject, listElement) {
  //iterate through the array or object
  for (var i in jsonObject) {
    //insert the next child into the list as a <li>
    var newLI = document.createElement("li");
    newLI.innerHTML += jsonObject[i];
    listElement.appendChild(newLI);
  }
}
<div class="dropdown-container">
<!--  <ul class="swatches" id="swatches" onchange="swatchIndex()">-->
  <ul class="swatches" id="swatches" onchange="swatchIndex()">
    <li class="cell" id="cell">
      None
      <div class="colorBox"></div>
      <!--END COLOR BOX-->
    </li>
    <!--END LI-->
  </ul>
  <!--END SWATCHES-->
</div>

any ideas out there?

Harsh Bansal

add extra [] to your string and use the code below:

var myObject = eval('(' + myJSONtext + ')');

test this using this.

var s =" [{'id':1,'name':'Test1'},{'id':2,'name':'Test2'}]"; var myObject = eval('(' + s + ')'); for (i in myObject) { alert(myObject[i]["name"]); }

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related