4 ms·
> Generating JSON data using string interpolation or templating is clearly wildly insane, right? You don’t do it. I'm sorry to report that I've seen a lot of J
by jlokier 3y ago
> Generating JSON data using string interpolation or templating is clearly wildly insane, right? You don’t do it.
I'm sorry to report that I've seen a lot of JSON generated by string concatenation and templating, in different projects.
Often using 'printf' or 'echo' in various languages. Sometimes using whatever's used for HTML string templating if the JSON is embedded in HTML or served as a resource similar to HTML.
Yes, its horrible and breaks if fed variable values that have characters like quotation marks in. People do it anyway.
Even in languages that have perfectly good data structures and JSON libraries.
I've seen a fair amount of parsing values out of JSON using regexes too, assuming specific formatting of the supplied JSON.
- jameshart 3y agoBut unlike with HTML I don’t think anyone’s going to jump in here and say ‘well yeah! Of course people do that because JSON is just text!’ I think everyone agrees that those approaches with JSON are bad.
- a1369209993 3y agoWell yeah! Of course people do that because JSON is just text! It's less common, because JSON is simpler, so the tradeoff point for using a grammar is lower, but it still makes sense in things like shell scripts, and other cases where the equivalent of `print(obj)` (or `eval(totally_not_rce)`, but let's pretend that's not available anyway) doesn't happen to produce (or consume) valid JSON by coincidence. # Using: grep -oP '(?<="bar": ")[^"]+' foo.json # and printf("{\"count\": %i, \"type\": \"%s\"}\n",nfoo,tfoo); is a general-purpose solution that can be adapted to pretty much any text-based format just by looking at examples, without having to cross-reference with a external specification (that the thing you're feeding input to or pulling output from may not even correctly implement anyway), so obviously people do that! See also various discussions under the heading "Worse is Better". Whether it's the right thing or the wrong thing, it very clearly is a thing.
- jameshart 3y agoOh.