I am using urfave/cli for my go program and I would like to have a cli flag that reads a json value like this one:
{"name":"foo","surname":"var"}
I am currently reading that variable as a cli.StringFlag which returns a string. Then, I was planning to json.Unmarshall it but it does not work. The problem is that the returned string by the cli library is like this:
[{name foo} {surname var}]
which is not a json anymore.
Is there a way to achieve this? Note that if it returned a simple map, that would work too
CodePudding user response:
for Linux, try to pass the paramaters with shell escape
#!/bin/bash
echo "{\"name\":\"foo\",\"surname\":\"var\"}"
in go program, just marshal this string parameter
CodePudding user response:
The issue is that the shell (bash, ksh, csh, zsh, ...) interprets
{"name":"foo","surname":"var"}
as a sequence of bareword and quoted word tokens:
| Token Type | Value |
|---|---|
| bareword | { |
| quoted word | name |
| bareword | : |
| quoted word | foo |
| bareword | , |
| quoted word | surname |
| bareword | : |
| quoted word | var |
| bare word | } |
As it happens, a comma (,) is a shell operator, used for arithmetic, and that essentially gets discarded (at least in zsh, what I use).
The whole is then spliced together to get
name:foo surname:var
You can see this in action by opening your shell and executing the command
echo {"name":"foo","surname":"var"}
If, however, you quote your JSON document with single quotes ('):
echo '{"name":"foo","surname":"var"}'
You'll get what you might expect:
{"name":"foo","surname":"var"}
Note, however, that this will fail if the text in your JSON document contains a literal apostrophe/single quote (', U 0027), so you'd want to replace all such occurrences within the JSON document with \, to escape them.
