libxo icon indicating copy to clipboard operation
libxo copied to clipboard

Best approach to create a nested JSON object

Open user19820 opened this issue 1 year ago • 3 comments

Hello!

I'm using libxo's cli utility in a set of scripts I'm writing to automate curl requests to a dev server. One of my requests requires a field that is in itself a json-encoded string. Is there a good way to do this using xo? I was thinking something along the lines of the golang %v verb, that would just allow any value to be inside the formatted string.

user19820 avatar Jun 25 '24 07:06 user19820

Please help me understand what you're looking for. Is it just a passthru, like::

const char *foo = "{ "one": 4, "two": 55 }"; xo_emit("foo: {foo/J}", foo);

where you are wanting::

"foo": { "one": 4, "two": 55 }

What would this for the "--libxo xml" or "pretty", given that I don't want to carry a JSON parser? I guess I could punt on both of those and make:

{ "one": 4, "two": 55 }

and ignore pretty (which would be pretty ugly).

Thanks, Phil

philshafer avatar Jul 02 '24 16:07 philshafer

My use case was creating a JSON structure which contained a nested JSON object as one of the fields. In my use case I'm using the xo cli utility to generate the JSON. I don't remember what the exact issue I ran into is, but I solved it with jq. The jq equivalent is:

formatJSON()
{
jq -n \
--arg orgid "${orgid}" \
--arg tokenid "${tokenid}" \
--arg name "$name" \
--argjson filters "${filters}" \
'{organizationId: ($orgid|tonumber), tokenId: $tokenid, name: $name, filters: ($filters|tostring)}'
}

I ran into issues when I was trying to generate the filters field

user19820 avatar Jul 03 '24 07:07 user19820

If your field is string trusted to always contain valid JSON and you don't care about pretty formatting it's enough to use the no-quotes field modifier like this"{Lwc:Filter}{n:filter}\n". I don't know a sane way to inject existing JSON into the (JSON) output. The only correct way that comes to mind is parsing it and using libxo to emit it recursively (scalar by scalar, list by list, container by container) which is unreasonable (slow, fragile, complex).

Crest avatar Oct 25 '24 15:10 Crest