Skip to content

Commit

Permalink
Implement JsonParseHelper
Browse files Browse the repository at this point in the history
  • Loading branch information
eschleb committed May 30, 2024
1 parent 2528721 commit bc2c204
Show file tree
Hide file tree
Showing 3 changed files with 45 additions and 0 deletions.
6 changes: 6 additions & 0 deletions Helpers.md
Original file line number Diff line number Diff line change
Expand Up @@ -219,4 +219,10 @@ Truthiness of arguments is determined by [Handlebars.Utils.isEmpty(Object)](http
```handlebars
{{#if (not (if a '===' b)) }} a does not equal b {{/if}}
{{#not (if a '===' b) }} a does not equal b {{/not}}
```

### [JsonParser](light-development/src/main/java/com/merkle/oss/magnolia/renderer/handlebars/helpers/JsonParseHelper.java)
Can be used to pass parsed json to other helpers. Arrays,objects and primitives are supported.
```handlebars
{{pattern name='somePattern' someJsonObjectProperty=(parse-json '{"key": "value"}')}}
```
4 changes: 4 additions & 0 deletions light-development/pom.xml
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,10 @@
<groupId>com.google.auto.factory</groupId>
<artifactId>auto-factory</artifactId>
</dependency>
<dependency>
<groupId>com.google.code.gson</groupId>
<artifactId>gson</artifactId>
</dependency>

<!-- TESTING DEPENDENCIES -->
<dependency>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
package com.merkle.oss.magnolia.renderer.handlebars.helpers;

import java.io.IOException;
import java.util.List;
import java.util.Map;
import java.util.Set;

import com.github.jknack.handlebars.Options;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;

public class JsonParseHelper implements NamedHelper<String> {
private final Gson gson = new GsonBuilder().create();

public Object apply(final String json, final Options options) throws IOException {
final JsonElement jsonElement = JsonParser.parseString(json);
if(jsonElement.isJsonArray()) {
return gson.fromJson(jsonElement.getAsJsonArray(), List.class);
}
if(jsonElement.isJsonObject()) {
return gson.fromJson(jsonElement.getAsJsonObject(), Map.class);
}
if(jsonElement.isJsonPrimitive()) {
return json;
}
return null;
}

@Override
public Set<String> names() {
return Set.of("parse-json");
}
}

0 comments on commit bc2c204

Please sign in to comment.