.toJSON()
Categories: Attributes
.toJSON( [ options ] )Returns: String
Plugin: jQuery.fn.json
Description: Transform the first element in the set of matched elements to JSON format.
-
.toJSON( [ options ] )
version added: 1.0options A map of additional options pass to the method.
The .toJSON()
method convert the DOM structure of the first element in the set of matched elements,
to a JSON string.
-
Convert XMl to JSON string.
XML:
<list> Start <entry full-name="Number 1"> <nr>1</nr> <category>Tests</category> <desc> <p>Text of no. 1.</p> <a hre="entry/1/more.html">more...</a> </desc> </entry> <entry full-name="Number 2"> <nr>2</nr> <category>Tests</category> <category>Advanced</category> <desc> <p>Text of no. 2.</p> <a hre="entry/2/more.html">more...</a> </desc> </entry> End </list>
Code:
$('list').toJSON();
Results:
{ "entry": [{ "nr": "1", "category": "Tests", "desc": { "p": "Text of no. 1.", "a": { "href": "entry/1/more.html", "text": "more..." } }, "full-name": "Number 1" }, { "nr": "2", "category": ["Tests", "Advanced"], "desc": { "p": "Text of no. 2.", "a": { "href": "entry/2/more.html", "text": "more..." } }, "full-name": "Number 2" }], "text": ["Start", "End"] }
-
Convert XMl to JSON string.
XML:
<list> Start <entry full-name="Number 1"> <nr>1</nr> <category>Tests</category> <desc> <p>Text of no. 1.</p> <a hre="entry/1/more.html">more...</a> </desc> </entry> <entry full-name="Number 2"> <nr>2</nr> <category>Tests</category> <category>Advanced</category> <desc> <p>Text of no. 2.</p> <a hre="entry/2/more.html">more...</a> </desc> </entry> End </list>
Code:
$('list') .toJSON({ camelCase: true, multiple: 'entry > category', cdata: 'entry > desc' });
Results:
{ "entry": [{ "nr": "1", "category": ["Tests"], "desc": "<p>Text of no. 1.</p><a href=\\"entry/1/more.html\\">more...</a>", "fullName": "Number 1" }, { "nr": "2", "category": ["Tests", "Advanced"], "desc": "<p>Text of no. 2.</p><a href=\\"entry/2/more.html\\">more...</a>", "fullName": "Number 2" }], "text": ["Start", "End"] }
-
Convert XMl to JSON string.
XML:
<list> Start <entry full-name="Number 1"> <nr>1</nr> <category>Tests</category> <desc> <p>Text of no. 1.</p> <a hre="entry/1/more.html">more...</a> </desc> </entry> <entry full-name="Number 2"> <nr>2</nr> <category>Tests</category> <category>Advanced</category> <desc> <p>Text of no. 2.</p> <a hre="entry/2/more.html">more...</a> </desc> </entry> End </list>
Code:
$('list') .toJSON({ extended: true });
Results:
{ "entry": [{ "nr": [{ "text": ["1"] }], "category": [{ "text": ["Tests"] }], "desc": [{ "p": [{ "text": ["Text of no. 1."] }], "a": [{ "href": "entry/1/more.html", "text": ["more..."] }] }], "full-name": "Number 1" }, { "nr": [{ "text": ["2"] }], "category": [{ "text": ["Tests"] }, { "text": ["Advanced"] }], "desc": [{ "p": [{ "text": ["Text of no. 2."] }], "a": [{ "href": "entry/2/more.html", "text": ["more..."] }] }], "full-name": "Number 2" }], "text": ["Start", "End"] }