RingDotNetfor Ring

JSON as a tree

JsonDocument reads JSON but cannot change it. JsonNode, JsonObject and JsonArray give you a tree that you can read, edit and build. This lesson changes a configuration, builds a report, merges settings with defaults, and clones a tree.

What you will learn#

These classes are in System.Text.Json.Nodes. The tutorial JSON and XML read JSON with JsonDocument; that class is fast but read-only. Use the nodes when you need to change JSON: configuration files, request bodies, data you assemble.

The program#

samples/UsingDotNet/tutorials/ch02_json_nodes.ring
# JSON as a tree you can change - JsonNode, JsonObject and JsonArray (System.Text.Json.Nodes)
load "dotnet.ring"

using {
	"System"
	"System.Text.Json"
	"System.Text.Json.Nodes"
}

C_CONFIG = '{"name":"shop","port":8080,"debug":false,"tags":["web","sql"],"database":{"host":"localhost","pool":5}}'

func main

	# 1. Parse text into a tree. A JsonNode is an object, an array or a value; AsObject() and AsArray() give the specific class.
	oRoot = new JsonNode().Parse(C_CONFIG).AsObject()
	? "1. name = " + oRoot.Item("name").ToString() + ", port + 1 = " + (number(oRoot.Item("port").ToString()) + 1)

	# 2. Walk down: Item("key") for an object, Item(index) for an array (the first item is index 0)
	? nl + "2. database.host = " + oRoot.Item("database").Item("host").ToString()
	oTags = oRoot.Item("tags").AsArray()
	? "   " + oTags.Count + " tags, the first is " + oTags.Item(0).ToString()
	? "   path of the first tag: " + oTags.Item(0).GetPath()

	# 3. Change the tree: set a value, add a key, add an array item, remove a key
	oRoot.SetItem("port",9090)
	oRoot.Add([ :propertyName = "owner", :value = "Ann" ])
	oTags.Add("json")
	oRoot.Remove("debug")
	? nl + "3. after the changes:"
	? pretty(oRoot)

	# 4. Check what is there before you read it: ContainsKey, and a missing key is the .NET null
	? nl + "4. has 'owner': " + yesNo(oRoot.ContainsKey("owner")) + ", has 'debug': " + yesNo(oRoot.ContainsKey("debug"))
	oMissing = oRoot.Item("nothing")
	? "   reading a missing key gives null: " + yesNo(oMissing.isNull())
	? "   the kind of 'port': " + oRoot.Item("port").GetValueKind() + ", of 'tags': " + oRoot.Item("tags").GetValueKind()

	# 5. Build a new document from Ring values. Ring numbers and texts convert by themselves;
	#    a Ring True is the number 1, so write a real JSON true by parsing it.
	oNew = new JsonObject()
	oNew.Add([ :propertyName = "id", :value = 7 ])
	oNew.Add([ :propertyName = "title", :value = "Report" ])
	oNew.Add([ :propertyName = "final", :value = new JsonNode().Parse("true") ])
	oItems = new JsonArray()
	for nLine = 1 to 3
		oLine = new JsonObject()
		oLine.Add([ :propertyName = "line", :value = nLine ])
		oLine.Add([ :propertyName = "amount", :value = nLine * 10.5 ])
		oItems.Add(oLine)
	next
	oNew.Add([ :propertyName = "items", :value = oItems ])
	? nl + "5. a new document: " + oNew.ToJsonString(NULL)

	# 6. Merge: settings with defaults. Values of the second document win; objects are merged, so nothing else is lost.
	oDefaults = new JsonNode().Parse('{"port":80,"debug":true,"database":{"host":"db","pool":2,"timeout":30}}').AsObject()
	merge(oDefaults,oRoot)
	? nl + "6. defaults merged with our settings:"
	? pretty(oDefaults)

	# 7. DeepClone copies a whole tree; changes to the copy leave the original alone. DeepEquals compares trees by content.
	oCopy = oRoot.DeepClone().AsObject()
	oCopy.SetItem("port",1)
	? nl + "7. the clone has port " + oCopy.Item("port").ToString() + ", the original still " + oRoot.Item("port").ToString()
	? "   trees equal: " + yesNo(new JsonNode().DeepEquals(oRoot,oCopy)) + " (different ports), after copying again: " + yesNo(new JsonNode().DeepEquals(oRoot,oRoot.DeepClone()))

# the tree as indented text
func pretty oNode

	oOptions = new JsonSerializerOptions() {
		WriteIndented = True
	}
	return "   " + substr(oNode.ToJsonString(oOptions),char(10),nl + "   ")

# copy the keys of oSource into oTarget; where both are objects, merge them
func merge oTarget, oSource

	aSourceKeys = keysOf(oSource)
	for cKey in aSourceKeys
		oValue = oSource.Item(cKey)
		if oTarget.ContainsKey(cKey) and oTarget.Item(cKey).GetValueKind() = "Object" and oValue.GetValueKind() = "Object"
			merge(oTarget.Item(cKey).AsObject(),oValue.AsObject())
		else
			oTarget.SetItem(cKey,oValue.DeepClone())
		ok
	next

# the keys of a JsonObject: its text form is parsed again with JsonDocument and its properties listed
func keysOf oObject

	oDocument = new JsonDocument().Parse(oObject.ToJsonString(NULL))
	aKeys = []
	oEnumerator = oDocument.RootElement.EnumerateObject()
	aProperties = oEnumerator.toList()
	for oProperty in aProperties
		aKeys + oProperty.Name
	next
	oDocument.Dispose()
	return aKeys

func yesNo lValue

	if lValue
		return "yes"
	ok
	return "no"
Output
1. name = shop, port + 1 = 8081

2. database.host = localhost
   2 tags, the first is web
   path of the first tag: $.tags[0]

3. after the changes:
   {

     "name": "shop",

     "port": 9090,

     "tags": [

       "web",

       "sql",

       "json"

     ],

     "database": {

       "host": "localhost",

       "pool": 5

     },

     "owner": "Ann"

   }

4. has 'owner': yes, has 'debug': no
   reading a missing key gives null: yes
   the kind of 'port': Number, of 'tags': Array

5. a new document: {"id":7,"title":"Report","final":true,"items":[{"line":1,"amount":10.5},{"line":2,"amount":21},{"line":3,"amount":31.5}]}

6. defaults merged with our settings:
   {

     "port": 9090,

     "debug": true,

     "database": {

       "host": "localhost",

       "pool": 5,

       "timeout": 30

     },

     "name": "shop",

     "tags": [

       "web",

       "sql",

       "json"

     ],

     "owner": "Ann"

   }

7. the clone has port 1, the original still 9090
   trees equal: no (different ports), after copying again: yes

How it works#

Reading#

new JsonNode().Parse(text) gives a node; AsObject() and AsArray() give the specific class. oRoot.Item("name") is the child with that key and oTags.Item(0) the first array item (indexes start at 0, as in .NET). Every node has ToString() for simple values — numbers arrive as text, so number(oRoot.Item("port").ToString()) — and GetPath(), which names where the node lives ($.tags[0]). GetValueKind() tells Object, Array, String, Number, True, False or Null.

Changing#

WhatCall
set an existing valueoRoot.SetItem("port",9090)
add a keyoRoot.Add([ :propertyName = "owner", :value = "Ann" ])
remove a keyoRoot.Remove("debug")
add an array itemoTags.Add("json")

Add of an object has several forms, so the key-and-value form takes a list of named values (propertyName and value). A Ring text or number is converted to a JSON value for you.

Missing keys#

oRoot.Item("nothing") does not raise an error: it gives the .NET null, which arrives in Ring as an object that answers isNull() (the tutorial Paths and the environment). Check with ContainsKey when a key is optional.

Building#

Step 5 builds a report: a JsonObject with values, a JsonArray of JsonObjects. ToJsonString(NULL) writes compact JSON; with JsonSerializerOptions and WriteIndented = True it writes indented JSON (the pretty helper).

Warning

A Ring True is the number 1, so Add([ :propertyName = "final", :value = True ]) writes 1. To write a JSON true, parse it: new JsonNode().Parse("true"). The same applies to null: parse "null".

Merging#

merge(defaults, ours) copies each key of our settings into the defaults. Where both sides hold an object (database), it merges them one level deeper, so database.timeout from the defaults survives while database.host and pool come from our settings. The keys of a JsonObject are read by parsing its text again with JsonDocument and listing EnumerateObject(); DeepClone() makes sure that the copied values do not belong to two trees at once (a node can have only one parent).

Cloning and comparing#

DeepClone() copies a whole tree. Changing the clone (port → 1) leaves the original alone. DeepEquals(a, b) compares two trees by content, not by identity.

What you learned#

Exercises#

  1. Read a configuration file (the tutorial Settings) into a node, change one value and save it again.
  2. Write getPath(oRoot, "database.host") that follows a dotted path.
  3. Write removeNulls(oNode) that deletes all keys with null values, at every depth.
  4. Send the JSON of step 5 through the pipe of the tutorial Two programs talking.

Next#

XML in depth

RingDotNet — use .NET classes and methods from Ring programs. Screenshots and output on these pages come from the real samples.