Parse JSON in Sightly JS | Community
Skip to main content
This post is no longer active and is closed to new replies. Need help? Start a new post to ask your question.
Best answer by smacdonald2008
To parse Json with sightly; define a Java class with the Sightly component. In the Java class, use a Java API that parses Json. When combining Java and Sightly; you can do a lot. See this community  article to learn how to use Java and Sightly: https://helpx.adobe.com/experience-manager/using/creating-sightly-component.html       

6 replies

francisco_ribei
Level 6
October 16, 2015

If you have a JSON string you can use:

var object = JSON.parse(jsonString);

And then use the object to refer to the properties.

Runal_Trivedi
Level 6
October 16, 2015

If you are using JS-Use API then its ultimately JS at the end and parsing it is nothing but simply using the keys to get desired value out of JSON.

If you are using Java-Use API then the one I have been using to map JSON to java objects is GSON. GSON is pretty handy in converting JSON to JAVA Object and vice-versa.

- Runal

smacdonald2008
smacdonald2008Accepted solution
Level 10
October 16, 2015
To parse Json with sightly; define a Java class with the Sightly component. In the Java class, use a Java API that parses Json. When combining Java and Sightly; you can do a lot. See this community  article to learn how to use Java and Sightly: https://helpx.adobe.com/experience-manager/using/creating-sightly-component.html       
Community Advisor
October 16, 2015

This doesn't work for me, I have tried this following is js code

"use strict";
use(function() {
    var pages = {};
    pages.text = properties.get("pages");
pages.ctas = JSON.parse(properties.get("pages"));
   
    return pages;
});

 

When I call this in html 

 <div  data-sly-use.pages="card.js">
       <p> Json text ${pages.text}</p>
       <p> CTAs : ${pages.ctas}</p>
       
       </div

I get ${pages.text} displayed  however  ${pages.ctas} throws exception in error.log

07.07.2015 18:06:41.554 *ERROR* [0:0:0:0:0:0:0:1 [1436306801283] GET /content/veritas/en/testpage.html HTTP/1.1] com.day.cq.wcm.core.impl.WCMDeveloperModeFilter Error during include of SlingRequestPathInfo: path='/content/veritas/en/testpage/jcr:content/par/card', selectorString='null', extension='html', suffix='null'
org.apache.sling.api.SlingException: Cannot get DefaultSlingScript: org.mozilla.javascript.EcmaError: SyntaxError: Unexpected token: L (/apps/veritas/components/content/card/card.html#5)
    

Feike_Visser1
Adobe Employee
Adobe Employee
October 16, 2015

Can you print what is inside properties.get("pages")?

thanks,
feike

Nikash_Bahadur
Adobe Employee
Adobe Employee
August 23, 2018

Use Handlebars. There's no explicit api to parse json directly in sightly. Instead you can dump the json in a handlebar template which can display the json data.