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

Allow escaped json to survive rendering #5

Merged
merged 10 commits into from
Jul 21, 2023

Conversation

jbohanon
Copy link

Add option to .dump() strings instead of .getstd::string().

this is useful in cases where the output of the rendered template is expected to be valid JSON. For example:
Input:

{
  "foo": "\"bar\""
}

Template:

{
  "FOO": "{{ foo }}"
}

Output (without allowing escaped strings):

{
  "FOO": ""bar""
}

Output (allowing escaped strings):

{
  "FOO": "\"bar\""
}

@jbohanon jbohanon changed the base branch from envoy-gloo to envoy-gloo-main July 20, 2023 18:45
Comment on lines +60 to +67
// get the value as a dump() to properly escape values
val = value->dump();

// strip the leading and trailing " characters that are added by dump()
// if C++20 is adopted, val.starts_with and val.ends_with would clean this up a bit
val = val.substr(0,1) == "\"" && val.substr(val.length()-1,1) == "\""
? val.substr(1, val.length()-2)
: val;
Copy link

Choose a reason for hiding this comment

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

one last thing i just noticed.. if this is already known to be a string, can we just get the string value instead of dumping as json?

i.e.

// store a string in a JSON value
json j_string = "this is a string";

// retrieve the string value
auto cpp_string = j_string.template get<std::string>();

Copy link

Choose a reason for hiding this comment

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

Copy link
Author

Choose a reason for hiding this comment

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

The .get<std::string>() does not escape characters, whereas .dump() does.

Copy link

Choose a reason for hiding this comment

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

ah thanks, i misunderstood. lgtm

Copy link

@kdorosh kdorosh left a comment

Choose a reason for hiding this comment

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

@jbohanon jbohanon merged commit 2c441a3 into envoy-gloo-main Jul 21, 2023
@jbohanon jbohanon deleted the allow-escaped-json-fork branch July 21, 2023 20:08
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants