Search code examples
jsonrebolrebol3

Create JSON array using altjson library


I am using this JSON library for Rebol http://ross-gill.com/page/JSON_and_REBOL and I am struggling to find the correct syntax to create JSON arrays.

I tried this:

>> to-json [ labels: [ [ label: "one" ] [ label: "two" ] ] ]
== {{"labels":{}}}

I was hoping for something like:

== {{"labels": [ {"label": "one"}, {"label": "two"} ]}}

Solution

  • As suggested by @hostilefork using the inverse operation shows us how it works.

    >> load-json {{"labels": [ {"label": "one"}, {"label": "two"} ]}}                                                                           
    == make object! [
        labels: [
            make object! [
                label: "one"
            ]
            make object! [
                label: "two"
            ]
        ]
    ]
    

    So we need to create an object containing objects. compose/deep is needed to evaluate the nested ( ) so the objects are created.

    to-json make object! compose/deep [
        labels: [
            (make object! [ label: "one" ])
            (make object! [ label: "two" ])
        ]
    ]
    

    In addition to the object! approach there is another option with a simpler syntax:

    >> to-json [
        <labels> [
            [ <label> "one" ]
            [ <label> "two" ]
        ]
    ]
    == {{"labels":[{"label":"one"},{"label":"two"}]}}