returning json from a web service, seems to add slashes

returning json from a web service, seems to add slashes

by tim st.clair -
Number of replies: 2
Picture of Plugin developers

I have a rest web service that accepts and returns a json string.

The input is ok, but the output json seems to be passed through addslashes or something. I broke it down and found that even if I define my input and output as PARAM_RAW, it still seems to mess with it.

Here's the guts of the service broken down to its simplest form:

    public static function myservice_parameters() {

        return new external_function_parameters(

                array("json" => new external_value(PARAM_RAW, "The JSON input"))

        );

    }

    public static function myservice_returns() {

        return new external_value(PARAM_RAW, 'The updated JSON output');

    }


    public static function myservice($json) {

        $obj = json_decode($json, JSON_NUMERIC_CHECK);

        // stuff modifies $obj ... does work in the db .. etc        

        $json = json_encode($obj);

        error_log($json, 3, "/Users/tim/Sites/_test/my-errors.log");

        return $json;

    }

Now, if my input json looks like this:

{"test":[{"id":1},{"id":2}]}

then what gets put into my log file looks like this:

{"test":[{"id":1},{"id":2}]}

but what gets returned by the web service itself is a slashed string. 

"{\"test\":[{\"id\":1},{\"id\":2}]}"

I can deal with it but it just seems like the webservice is changing my return value even though I thought it shouldn't. I can't find great documentation about it (and reading externallib.php wasn't that helpful). Am I doing something wrong?

Average of ratings: -
In reply to tim st.clair

returning json from a web service, seems to add slashes

by Olexandr Berezhnyk -

Yes I have the same situation and don't know how to fix it.

In reply to tim st.clair

Re: returning json from a web service, seems to add slashes

by Tim Hunt -
Picture of Core developers Picture of Documentation writers Picture of Particularly helpful Moodlers Picture of Peer reviewers Picture of Plugin developers

If you want to return an object, return $obj.

json_encode($obj) is a string, and in order to safely send that string back to the client, special characters have to be escaped, and that is what is happening. However, you don't want a string, so don't do that.

Average of ratings: Useful (1)