Skip to content

Instantly share code, notes, and snippets.

@jonelf
Created November 1, 2021 12:38
Show Gist options
  • Save jonelf/106c5cdf86e0c556c165d575e6b8e9e0 to your computer and use it in GitHub Desktop.
Save jonelf/106c5cdf86e0c556c165d575e6b8e9e0 to your computer and use it in GitHub Desktop.
JSON strings can contain braces
JSON strings can contain {}.
test_data = ["{dsfgsdf}", "{asdf}, {sdfsdf}", "{{dfgd}, {sadf}}", "sdfd}{", "{asdfsad}, {sdfs}}", "{{asdf},{sdfsdf}", '{"test{{{"}, {"{{{fest"}']
test_data.each { |s|
instring = false;
res = s.split(//).reduce(0) { |sum, c|
break sum if sum < 0
instring = !instring if c == '"'
if !instring
sum +=1 if c == "{"
sum -=1 if c == "}"
end
sum
}
puts s + " is #{res != 0 ? "no ":""}good!"
}
@jonelf
Copy link
Author

jonelf commented Nov 1, 2021

Output:

{dsfgsdf} is good!
{asdf}, {sdfsdf} is good!
{{dfgd}, {sadf}} is good!
sdfd}{ is no good!
{asdfsad}, {sdfs}} is no good!
{{asdf},{sdfsdf} is no good!
{"test{{{"}, {"{{{fest"} is good!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment