英文:
Running Go from the command line nested JSON
问题
我可以想到一些解决方法来解决这个问题,但我对是否有解决这个特定问题的解决方案很感兴趣。
我有一个需要一个JSON字符串参数的Go程序:
go run main.go "{ "field" : "value" }"
到目前为止没有问题。然而,如果其中一个JSON值是另一个JSON字符串,我能否从命令行运行?
go run main.go "{ "json-string" : "{\"nestedfield\" : \"nestedvalue\"}" }"
似乎添加转义字符会错误地匹配起始和结束引号。我是否误解了这个操作的方式,还是(我倾向于这一方面)根本不可能?
再次强调,这是一个引起我的好奇心的问题 - 我知道还有其他方法 - 我希望得到与这个特定问题相关的输入。
英文:
I can think of workarounds on how to get this working however I'm interested in finding out if there's a solution to this specific problem.
I've got a go program which requires a json string arguement:
go run main.go "{ \"field\" : \"value\" }"
No problems so far. However, am I able to run from the command line if one of the json values is another json string?
go run main.go "{ \"json-string\" : \"{\"nestedfield\" : \"nestedvalue\"}\" }"
It would seem that adding escape characters incorrectly matches up the opening and closing quotes. Am I minuderstanding how this is done or is it (and this is the side I'm coming down on) simply not possible?
To reiterate, this is a question that has piqued my curiosity - I'm aware of alternative approaches - I'm hoping for input related to this specific problem.
答案1
得分: 1
为什么不将你的 JSON 配置放入文件中,并使用 flag 包将配置文件名提供给你的应用程序呢?
英文:
Why don't you just put your json config to the file and provide config file name to your application using flag package
答案2
得分: 0
根据wiredeye的反馈,我改用了参数路由。我修改了程序以在以下命令中运行:
go run main.go field:value field2:value json-string:"{"nestedfield":nestedvalue}"
然后,我可以迭代os.Args并在程序中获取嵌套的json。我没有直接使用标志(flags),因为我不知道程序中输入的数量,这将要求我使用重复的标志(不支持)或将标志解析为集合(似乎也不支持)。
谢谢wiredeye的建议。
英文:
Based on the feedback from wiredeye I went down the argument route instead. I've modified the program to run on:
go run main.go field:value field2:value json-string:"{\"nestedfield\":nestedvalue}"
I can then iterate over the os.Args and get the nested json within my program. I'm not using flags directly as I don't know the amount of inputs into the program which would have required me to use duplicate flags (not supported) or parse the flag to a collection (doesn't seem to be supported).
Thanks wiredeye
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论