Typescript is not going to make it better.
The problem is whoever is producing the data.
Typescript is not going to make it better.
The problem is whoever is producing the data.
I suppose what is wanted is something like
let parsedJSON = {}
try { parsedJSON = JSON.parse(susJsonString) } catch { //maybe register problem with parsing. }
JSON.parse(JSON.parse("\"{foo: 1}\""))
I'd guess the problem is something upstream. let susJsonString=JSON.stringify(JSON.stringify(JSON.stringify({foo:1})))
console.log("initial:", susJsonString);
try {
while(typeof susJsonString==='string') {
susJsonString = JSON.parse(susJsonString);
console.log("iteration:", typeof susJsonString, susJsonString);
}
} catch {
susJsonString = {};
}
I see: initial: "\"{\\\"foo\\\":1}\""
iteration: string "{\"foo\":1}"
iteration: string {"foo":1}
iteration: object {foo: 1}
A comment explaining the sort of "sus" input it was designed to cope with may have been helpful. while(typeof susJsonString==='string') {
susJsonString = JSON.parse(susJsonString);
as it'll keep reassigning and parsing until gets a non string back (or alternatively error out if the string is not valid json)let susJsonString = '...'
example
but evidently it is not just that it is serialized multiple times, otherwise it shouldn't need the try catch (of course one problem with online discussion of code examples is you must always assume, contra obvious errors, that the code actually needs what it has)
Something upstream, sure, but often not something "fixable" either, given third parties and organizational headaches some places are prone to.
The blanket catch is odd though, as I'd have thought that it would still be outputting valid json (even if it has been serialized multiple times), and if you're getting invalid json you probably want to know about that.
It’s applying the operation recursively.
Please take a lesson from this. Good code is not the one that follows all the rules you read online. Your coworker you dismissed understood the problem.
I think asking questions is ideal. Even when I'm 99% sure a line is blatantly wrong, I will ask something like, "What is this for?". Maybe I missed something - wouldn't be the first time.
I reserve my general opinion on the quality of this coder's work, as evidenced by the quality of the app itself among other things. But I guess you'd have to just trust (or not trust) me on that.