Expand my Community achievements bar.

SOLVED

Parse JSON in Sightly JS

Avatar

Level 6

I have json object. I want to parse it in sightly JS. Which API to use ?

1 Accepted Solution

Avatar

Correct answer by
Level 10
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       

View solution in original post

6 Replies

Avatar

Level 6

If you have a JSON string you can use:

var object = JSON.parse(jsonString);

And then use the object to refer to the properties.

Avatar

Community Advisor

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

Avatar

Correct answer by
Level 10
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       

Avatar

Level 9

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)
    

Avatar

Employee

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

thanks,
feike

Avatar

Employee

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.