2

I have a content type with a field called output. This field will contain JSON. I want to output this field as JSON using Views JSON (in Views Datasource). The problem I'm encountering is views datasource is a. wrapping my field in quotes, and b. escaping my double quotes...

    [
    {
    "content": "{\"account-confirmation\":{\"body\":\"\",...

I need it to return something like:

    [
    {
    "content": {"account-confirmation":{"body":"",...

I've tried everything I could possibly think of. Is there any way I can output the literal value of the field without wrapping the value in quotes and escaping quotes?

  • No, that's impossible by definition. JSON mandates that double quotes wrap all keys and values, so if you remove those double quotes, you no longer have JSON. It's not a problem, that's exactly how the module (and literally anything that produces a JSON string) is designed to work – Clive Sep 24 '15 at 7:44
  • True, however, my goal is to make "Account-confirmation" another object within "content", so the "account-confirmation" key would still be wrapped in double quotes, and would technically still be valid json, however it would not be a simple key/value pair, but a nested object. The end goal is unescaping all of those "/" and removing the first and last double quote that wraps the value of the "content" key. – user3408649 Sep 24 '15 at 10:45
  • Ohhhh right, yeah I get what you mean. My bad. Unless the module offers an alter hook, you're going to be patching it directly I think. Looks to me the current output would be the result of something like $inner_object = json_encode($account_confirmation); $main_obj = json_encode(array('content' => $inner_object));. That's got to be a bug, they can't have done that intentionally, surely – Clive Sep 24 '15 at 10:49
0

Views Datasource will escape the contents of any string field. If the field were an object, it would be formatted as JSON. (See: views_datasource/views/plugins/views_plugin_style_json.inc.) There doesn't seem to be any way to override this behaviour other than patching the module or using some field type that would produce this result.

I faced a somewhat related problem and had to write my own API endpoint to get the JSON as I wanted it. I used views_get_view_result() to get the raw data and rework it so that I had the correct array structure. Then I run drupal_json_encode().

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.