Earlier quoted context omitted.
That's awesome work. The only problem is that it does not properly handle keys which are not valid JS identifiers (like 1foo, @foo, foo-bar, etc.).
Well, there's this option without the blacklist: jq -r ' tostream | select(length > 1) | (.[0] | map("[" + @json + "]") | join("")) + " = " + (.[1] | @json) ' And this other option with the blacklist patterns: jq -r ' tostream | select(length > 1) | ( .[0] | map( if type == "number" or (tostring | test("[@-]|^[0-9]|^else$")) then "[" + @json + "]" else "." + . end ) | join("") ) + " = " + (.[1] | @json) ' (The blackl…
jq -r '
tostream
| select(length > 1)
| (
.[0] | map(
if tostring | (
test("^[A-Za-z$_][0-9A-Za-z$_]*$")
and (
. as $property
| ["if", "else"] | all(. != $property)
)
)
then "." + .
else "[" + @json + "]"
end
) | join("")
) + " = " + (.[1] | @json)
'
You whitelist against what the syntax allows for identifiers and then you blacklist reserved keywords. Writing it this way makes it easier to verify for correctness when comparing with the ECMAScript Specs. This is still a non-exhaustive blacklist and the whitelist regex lacks allowed unicode characters.