50 lines
No EOL
2.7 KiB
HTML
50 lines
No EOL
2.7 KiB
HTML
<HTML>
|
|
<HEAD>
|
|
<title>libjson Child Node Example</title>
|
|
<script type="text/javascript" src="scripts/shCore.js"></script>
|
|
<script type="text/javascript" src="scripts/shBrushCpp.js"></script>
|
|
<link type="text/css" rel="stylesheet" href="styles/shCoreDefault.css"/>
|
|
<script type="text/javascript">SyntaxHighlighter.all();</script>
|
|
|
|
</HEAD>
|
|
<BODY>
|
|
<h1>libjson Child Node Example</h1>
|
|
<p>Now we'll look at how to create a branch off the main tree.</p>
|
|
<p><span id="more-114"></span></p>
|
|
<pre class="brush:cpp;wrap-lines:true">JSONNODE *n = json_new(JSON_NODE);
|
|
json_push_back(n, json_new_a("RootA", "Value in parent node"));
|
|
JSONNODE *c = json_new(JSON_NODE);
|
|
json_set_name(c, "ChildNode");
|
|
json_push_back(c, json_new_a("ChildA", "String Value"));
|
|
json_push_back(c, json_new_i("ChildB", 42));
|
|
json_push_back(n, c);
|
|
json_char *jc = json_write_formatted(n);
|
|
printf("%s\n", jc);
|
|
json_free(jc);
|
|
json_delete(n);</pre>
|
|
|
|
<p>The result will look like this:</p>
|
|
<pre class="brush:cpp;wrap-lines:true">{
|
|
"RootA" : "Value in parent node",
|
|
"ChildNode" : {
|
|
"ChildA" : "String Value",
|
|
"ChildB" : 42
|
|
}
|
|
}</pre>
|
|
|
|
<p>As in the previous example, we create a root node to hold all of our child nodes on line one using <em>json_new</em>.</p>
|
|
<p>Line 2 adds to the root a string node with the name "RootA" and a value of "Value in parent node".</p>
|
|
<p>On line 3 we're creating a new, floating node that will be a branch off the root. It's the same type as our root, JSON_NODE.</p>
|
|
<p><em>json_set_name</em> lets us name the node that we've just created. If your branch is an object of some kind, you'll likely want to name it properly. Note that if you try to name the root node (<em>n</em> in our case), it won't be written out. The name will only appear if the JSON_NODE is a child of another node.</p>
|
|
|
|
<p>Lines 5 and 6 add new nodes with values to our branch node <em>c</em>.</p>
|
|
<p>Line 7 attaches our branch node <em>c</em> to the root node <em>n</em> after the string node named "RootA". Note that if you fail to attach the branch to another node, you'll have to delete it manually or risk a memory leak.</p>
|
|
<p>Line 8 returns the <em>json_char</em> string nicely formatted and 9 prints it to stdout.</p>
|
|
|
|
<p>Line 10 frees our JSON string and line 11 loops through our root tree and frees up the memory we've used.</p>
|
|
<p>With these tools, we can create complicated JSON structures and mimick objects with child properties.</p>
|
|
|
|
|
|
<p>Chris Larsen 2010-10-08</p>
|
|
<BODY>
|
|
</HTML> |