0

I have code which return a single Node.

var items = document.querySelectorAll('ul');
return items[0];

How can I convert it to JSON? For me method JSON.parse() doesn't work. It takes not Node but string object.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
Alex
  • 2,091
  • 6
  • 31
  • 49
  • `JSON.stringify()` takes a JavaScript object and serializes it to JSON if possible. – The Paramagnetic Croissant Oct 29 '14 at 13:29
  • What node are you trying to convert? What are you trying to convert it to? – lonesomeday Oct 29 '14 at 13:29
  • ... Because parsing parses JSON. `JSON.stringify` makes JSON. But it's not clear what you actually want to get from the unordered list as JSON. – Dave Newton Oct 29 '14 at 13:30
  • 1
    JSON doesn't have an HTMLElementNode data type, so you can't convert it directly. If you had some specific translation in mind then you'd need to explain that. – Quentin Oct 29 '14 at 13:31
  • DOM nodes contain circular references, so it's not possible to just convert it. You have build a new object with the information you want. – Felix Kling Oct 29 '14 at 13:34
  • 1
    You can't just convert a javascript Node object into JSON as it's deeply nested and contains native DOM functions and properties. You'll have to convert this manually by just getting only properties that you require. – andyw_ Oct 29 '14 at 13:34
  • Hm... when I use `JSON.stringify` I get `Converting circular structure to JSON`. – Alex Oct 29 '14 at 13:34
  • 2
    @Alex: That's what several people said would happen already. You need to create a new object with only the properties you'd like (e.g. `var myObject = { id: items[0].id, title: items[0].title };`; then, convert it: `var json = JSON.stringify(myObject);`). – Cᴏʀʏ Oct 29 '14 at 13:36
  • @Alex Because that's not what you really want to do--you want to get the *contents* of the list nodes as JSON, *probably*. You don't actually say what you want, which is why everybody is asking that. – Dave Newton Oct 29 '14 at 13:36

0 Answers0