2

This should be simple, but I couldn't figure this out while debugging a grease monkey script. Can a JQuery object, such as a single element, be converted to JSON? e.g. JSON.stringify($("<p />")) I've gotten a cyclical reference errors.

I've been experimenting here: http://jsfiddle.net/q7ywV/2/

html

<p> whatever </p>
<p> whatever2 </p>

js

try {
  zoom = JSON.stringify($("p").eq(0));
  console.log(zoom);
}
catch (e) {
    console.log(e);
}
TonyH
  • 1,117
  • 8
  • 18
  • I also tried the cycle.js library to handle this via JSON-Path. Using a non-native JSON.stringify, I get stack errors. – TonyH Jul 22 '12 at 18:54
  • Stupidly, I had already mostly figured this out, the issue is that DOM elements contain circular references by design, as mentioned in http://stackoverflow.com/a/4277815/657764 I'm not sure why JSON.decycle doesn't work though. Maybe the object is too big? – TonyH Jul 22 '12 at 18:57

2 Answers2

1

You cannot pass dom and expect as a json. You can store it as an array convert as JSOn and then use JSON.stringify

Also, your method of getting string is wrong. Below should work just for string. You can do similar with one or more html elements store as an array and then use stringify. http://jsfiddle.net/q7ywV/13/

user1269989
  • 117
  • 1
  • 5
0

Apparently, JSON is not designed to represent complicated objects like DOM elements. Simple objects only.

TonyH
  • 1,117
  • 8
  • 18
  • 2
    It's not the complexity, it's the circular references. Regardless how complex the object is, it should be possible to stringify it if it doesn't contain circular references. – Šime Vidas Jul 22 '12 at 19:01
  • 1
    I found it interesting that Douglas Crockford's cycle.js [link](https://github.com/douglascrockford/JSON-js/) couldn't deal with (or decycle) a DOM element. What would it take? – TonyH Jul 22 '12 at 23:47