Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add fromJson and mustFromJson funcs #223

Merged
merged 1 commit into from
Dec 2, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
13 changes: 13 additions & 0 deletions defaults.go
Original file line number Diff line number Diff line change
Expand Up @@ -63,6 +63,19 @@ func coalesce(v ...interface{}) interface{} {
return nil
}

// fromJson decodes JSON into a structured value, ignoring errors.
func fromJson(v string) interface{} {
output, _ := mustFromJson(v)
return output
}

// mustFromJson decodes JSON into a structured value, returning errors.
func mustFromJson(v string) (interface{}, error) {
var output interface{}
err := json.Unmarshal([]byte(v), &output)
Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This will silently fail if v cannot be converted to a []byte. The type conversion should be checked.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That's a compile time check. I believe all strings can be converted to byte slices. (This is not a type assertion.)

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, you're right. However, I would extend the function to also accept []byte as an input.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why?

Copy link

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Data flowing between template functions can be of any type. It's entirely possible that someone will want to use this function with a []byte, for example:

{{ (readFile "foo.json" | fromJson).bar }}

where readFile returns a []byte. Why not allow this?

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We can. I was just wondering what the use case was.

return output, err
}

// toJson encodes an item into a JSON string
func toJson(v interface{}) string {
output, _ := json.Marshal(v)
Expand Down
16 changes: 16 additions & 0 deletions defaults_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,22 @@ func TestCoalesce(t *testing.T) {
}
}

func TestFromJson(t *testing.T) {
dict := map[string]interface{}{"Input": `{"foo": 55}`}

tpl := `{{.Input | fromJson}}`
expected := `map[foo:55]`
if err := runtv(tpl, expected, dict); err != nil {
t.Error(err)
}

tpl = `{{(.Input | fromJson).foo}}`
expected = `55`
if err := runtv(tpl, expected, dict); err != nil {
t.Error(err)
}
}

func TestToJson(t *testing.T) {
dict := map[string]interface{}{"Top": map[string]interface{}{"bool": true, "string": "test", "number": 42}}

Expand Down
9 changes: 9 additions & 0 deletions docs/defaults.md
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,15 @@ The above will first check to see if `.name` is empty. If it is not, it will ret
that value. If it _is_ empty, `coalesce` will evaluate `.parent.name` for emptiness.
Finally, if both `.name` and `.parent.name` are empty, it will return `Matt`.

## fromJson, mustFromJson

`fromJson` decodes a JSON document into a structure. If the input cannot be decoded as JSON the function will return an empty string.
`mustFromJson` will return an error in case the JSON is invalid.

```
fromJson "{\"foo\": 55}"
```

## toJson, mustToJson

The `toJson` function encodes an item into a JSON string. If the item cannot be converted to JSON the function will return an empty string.
Expand Down
2 changes: 1 addition & 1 deletion docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ The Sprig library provides over 70 template functions for Go's template language
- [Math Functions](math.md): `add`, `max`, `mul`, etc.
- [Integer Slice Functions](integer_slice.md): `until`, `untilStep`
- [Date Functions](date.md): `now`, `date`, etc.
- [Defaults Functions](defaults.md): `default`, `empty`, `coalesce`, `toJson`, `toPrettyJson`, `toRawJson`, `ternary`
- [Defaults Functions](defaults.md): `default`, `empty`, `coalesce`, `fromJson`, `toJson`, `toPrettyJson`, `toRawJson`, `ternary`
- [Encoding Functions](encoding.md): `b64enc`, `b64dec`, etc.
- [Lists and List Functions](lists.md): `list`, `first`, `uniq`, etc.
- [Dictionaries and Dict Functions](dicts.md): `get`, `set`, `dict`, `hasKey`, `pluck`, `deepCopy`, etc.
Expand Down
2 changes: 2 additions & 0 deletions functions.go
Original file line number Diff line number Diff line change
Expand Up @@ -216,9 +216,11 @@ var genericMap = map[string]interface{}{
"coalesce": coalesce,
"compact": compact,
"mustCompact": mustCompact,
"fromJson": fromJson,
"toJson": toJson,
"toPrettyJson": toPrettyJson,
"toRawJson": toRawJson,
"mustFromJson": mustFromJson,
"mustToJson": mustToJson,
"mustToPrettyJson": mustToPrettyJson,
"mustToRawJson": mustToRawJson,
Expand Down