run from Shell R function with json string parameter

By : Marta
Source: Stackoverflow.com
Question!

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!

By : Marta


Answers

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.

By : nstjhp


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.



This video can help you solving your question :)
By: admin