Files
bson2json/bson2json.nim
2021-08-12 10:02:30 -07:00

113 lines
2.8 KiB
Nim

## Convert bson to/from json documents
import oids
import json except `%*`
import nimongo.bson except `%*`
########################################################################
## Convert a json document to a bson document.
##
proc toBson*(js: JsonNode): Bson =
## Convert JsonNode object to a Bson document
case js.kind:
of JInt:
return js.getInt().toBson()
of JString:
return js.getStr().toBson()
of JFloat:
return js.getFloat().toBson()
of JBool:
return js.getBool().toBson()
of JNull:
return null()
of JObject:
var b = newBsonDocument()
for k, v in js:
b[k] = v.toBson()
return b
of JArray:
var b = newBsonArray()
for i in 0 ..< len(js):
b.add js[i].toBson()
return b
else:
echo "Unknown JsonNode type: ", js.repr
########################################################################
## Convert a bson document to a json document.
##
proc toJson*(bs: Bson): JsonNode =
## Convert Bson document to Json node
case bs.kind:
of BsonKindDouble:
return % bs.toFloat64()
of BsonKindOid:
return % $(bs.toOid())
of BsonKindStringUTF8:
return % bs.toString()
of BsonKindInt64:
return % bs.toInt64()
of BsonKindInt32:
return % bs.toInt32()
of BsonKindBool:
return % bs.toBool()
of BsonKindTimeUTC:
return % $(bs.toTime())
of BsonKindTimestamp:
return % $(bs.toTimestamp())
of BsonKindDocument:
var js = newJObject()
for k, v in bs:
js[k] = v.toJson()
return js
of BsonKindArray:
var js = newJArray()
for v in bs:
js.add(v.toJson())
return js
else:
raise newException(ValueError, "Unknown bson node type: " & $ord(bs.kind))
when isMainModule:
import times
const jsTxt = """
{
"base": "USD",
"@timestamp": "1516710051111",
"arrays": {
"strings": ["uno", "dos", "tres"],
"ints": [111, 222, 333],
"floats": [1.11, 2.22, 3.33],
"mixed": ["uno", 222, 3.33],
"objects": [
{"name": "first", "id": 1, "values": [1, 2, 3]},
{"name": "second", "id": 2, "values": [2, 4, 6]},
{"name": "third", "id": 3, "values": [3, 6, 9]}
]
},
"rates": {
"CNY": 6.4019,
"JPY": 110.537003,
"UGX": 3627.0
},
"currencies": {
"CNY": "Chinese Yuan",
"JPY": "Japanese Yen",
"UGX": "Ugandan Shilling",
"USD": "US Dollar"
}
}
"""
echo "** Parse text js into JsonNode object"
let jsDoc = parseJson(jsTxt)
echo "** Convert JsonNode object to Bson"
let bsDoc = jsDoc.toBson()
echo "** Convert Bson document to JsonNode object (round-trip)"
let jsRtDoc = bsDoc.toJson()
echo "** Compare:"
if jsDoc == jsRtDoc:
echo ">>>> Roundtrip conversion was a success!!"
else:
echo "++++ Roundtrip conversion failed!!"
# Fin.