Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Best approach to create a nested JSON object #95

Open
akalpaki opened this issue Jun 25, 2024 · 3 comments
Open

Best approach to create a nested JSON object #95

akalpaki opened this issue Jun 25, 2024 · 3 comments

Comments

@akalpaki
Copy link

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.

@philshafer
Copy link

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

@akalpaki
Copy link
Author

akalpaki commented Jul 3, 2024

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

@Crest
Copy link

Crest commented Oct 25, 2024

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).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants