4 ms·
That's quite different though. It looks to be dealing with the case that a serialised object gets serialiased multiple times before it reaches that point of cod
by accoil 2y ago
That's quite different though. It looks to be dealing with the case that a serialised object gets serialiased multiple times before it reaches that point of code, so it needs to keep deserialising until it gets a real object. E.g:
JSON.parse(JSON.parse("\"{foo: 1}\""))
I'd guess the problem is something upstream.
- darepublic 2y agoThe code is either going to loop once and exit or loop forever no
- andrewf 2y agoPutting this in my web console: 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.
- accoil 2y agoIt will stop when it gets something that's not a string due to 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)
- bryanrasmussen 2y agoHmm, yeah ok, didn't pick this out of the 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.
- accoil 2y agoYeah. I imagine that's a bandaid around having to consume a dodgy api that they didn't have access/permission to fix. 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.
- bryanrasmussen 2y agoprobably some times the api comes out with an empty string.