run from Shell R function with json string parameter

主宰稳场 提交于 2019-12-25 02:39:22

问题


I have function, that works with json string. When I try in R:

 my_function('{"menu":{"id":"file","value":"File","popup":{"menuitem":[{"value":"New","onclick":"CreateNewDoc()"},{"value":"Open","onclick":"OpenDoc()"},{"value":"Close","onclick":"CloseDoc()"}]}}}')

it works well.

But when I try in Shell command:

 R -e "source('./my_function.R'); my_function('{"menu":{"id":"file","value":"File","popup":{"menuitem":[{"value":"New","onclick":"CreateNewDoc()"},{"value":"Open","onclick":"OpenDoc()"},{"value":"Close","onclick":"CloseDoc()"}]}}}')"

It fails with error:

unexpected character 'm'

.

Seems, that problem is with quotes in json string. How can I solve it?

P.S. I need to call my_function directly from Shell.

Thank you!


回答1:


Write it main script like main.r,

source('./my_function.R')
my_function('{"menu":{"id":"file","value":"File","popup":{"menuitem":[{"value":"New","onclick":"CreateNewDoc()"},{"value":"Open","onclick":"OpenDoc()"},{"value":"Close","onclick":"CloseDoc()"}]}}}')"

Execute it from command terminal like,

Rscript main.r 

please make sure you have R path configured.




回答2:


You can't mix the quotes as you are doing. The shell is reading from your opening double quotes until the first double quotes it finds ( which is in your JSON string). It then sees an m (in menu) which it can't handle and gives the error message.



来源:https://stackoverflow.com/questions/22221113/run-from-shell-r-function-with-json-string-parameter

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!