run from Shell R function with json string paramet

2019-09-06 06:36发布

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!

2条回答
等我变得足够好
2楼-- · 2019-09-06 07:02

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.

查看更多
beautiful°
3楼-- · 2019-09-06 07:11

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.

查看更多
登录 后发表回答