Search code examples
jsonaemslingjcr

AEM JCR - Get response as JSON


We are adding some metadata under a specific location in JCR:

POST /some/jcr/location/_jcr_content/json HTTP/1.1
Accept: application/json
Authorization: Basic YWRtaW46YWRtaW4=
Cache-Control: no-cache
Host: localhost:4502
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Content-Type: multipart/form-data; boundary=--------------------------554953211468377919703514
Cookie: cq-authoring-mode=TOUCH
Content-Length: 383
----------------------------554953211468377919703514
Content-Disposition: form-data; name="./value"

{ "test": "test" }
----------------------------554953211468377919703514
Content-Disposition: form-data; name=":cq_csrf_token"

ey***our csrf token***-c5Oa0
----------------------------554953211468377919703514--

But when we fetch this same resource, the response type is test/html`:

GET /some/jcr/location/jcr:content/json/value HTTP/1.1
Accept: application/json
Cache-Control: no-cache
Host: localhost:4502
Accept-Encoding: gzip, deflate, br
Connection: keep-alive
Cookie: cq-authoring-mode=TOUCH

HTTP/1.1 200 OK
Date: Fri, 26 Feb 2021 13:49:38 GMT
X-Content-Type-Options: nosniff
Content-Type: text/plain;charset=utf-8 
Content-Length: 18
{ "test": "test" }

What configuration do we need to add in JCR, or what do we need to edit in our request to make sure that JCR returns content type application/json.

UPDATE: As Sharath Madappa replied, you can request the data in JSON format by suffixing the location with the .json extension. However, that results in the following format:

{
    "value": "{ \"test\": \"test\" }"
}

While I expect it to be:

{
    "test": "test"
}

Solution

  • Posting JSON content and then retrieving it as Content-Type: application/json can be done by file upload instead of adding properties.

    Here is a javascript example:

    const data = { test: "test" };
    const jsonData = new Blob([JSON.stringify(data)], { type: 'application/json' });
    const formData = new FormData();
    formData.append(`myFile.json`, jsonData, `myFile.json`);
    
    return fetch(path, {
      method: 'POST',
      body: formData
    });
    

    This example does not take in account Authn/Authz.

    To fetch you data as application/json, you just issue a GET call to the location of the JSON file:

    http://localhost:4502/path/to/the/folder/jcr:content/files/myFile.json