New to nim and trying to create some json nodes with very little luck. Here's what I have so far (areas is just alist of strings). The end result needs to be a set of json nodes that will be added as subnodes to another json node. I need to create a group of nodes that look just like areaJson below, but with the value of value changes for every area in areas:
var
ifoAreas: seq[JsonNode]
areaJson = %* {"__struct_id":6,"Area_Name":{"type":"resref","value":"value"}}
for area in areas:
areaJson["Area_Name"].add("value", newJString(area))
ifoAreas.add(areaJson)
After the first iteration, ifoAreas has the following value, which is correct:
@[{"__struct_id":6,"Area_Name":{"type":"resref","value":"area001"}}]
It then builds the nodes exactly how I want, but the value of all the nodes changes to the most recent area value.
@[{"__struct_id":6,"Area_Name":{"type":"resref","value":"area002"}},
{"__struct_id":6,"Area_Name":{"type":"resref","value":"area002"}}]
I want to get the following:
@[{"__struct_id":6,"Area_Name":{"type":"resref","value":"area001"}},
{"__struct_id":6,"Area_Name":{"type":"resref","value":"area002"}}]
What do I need to do to make that happen? I feel like it's very obvious, but my attempts to make things happen by perusing the json.nim and trying the various methods in there have all failed. This is the closest I've come to getting it to work, just can't seem to get the area values to stick. Thanks!Hello! Your problem comes from the fact that JsonNode is a "ref object", so you're actually adding the same JsonNode and modifying it each time in the loop, that's why you get all duplicates (they refer to the same value). To fix it, you can for example create your node in the loop itself:
import json
let areas = @["value0", "value1", "value2"]
var
ifoAreas: seq[JsonNode]
for area in areas:
let areaJson = %*{"__struct_id":6, "Area_Name": {"type": "resref", "value": area}}
ifoAreas.add(areaJson)
echo ifoAreas