Path: csiph.com!fu-berlin.de!uni-berlin.de!individual.net!not-for-mail From: Arno Welzel Newsgroups: comp.lang.php Subject: Re: JSON encode "corrupted"? Date: Sun, 8 Aug 2021 11:43:11 +0200 Lines: 55 Message-ID: References: Mime-Version: 1.0 Content-Type: text/plain; charset=utf-8 Content-Transfer-Encoding: 7bit X-Trace: individual.net Db6kgM8/ZAMDKtkJEEFXMQC2YYs/ZzrYSKChieFL2tE4KpIAsn Cancel-Lock: sha1:hf9gsGLVQX1lp7QtmFIGwhF3tts= In-Reply-To: Xref: csiph.com comp.lang.php:18764 Lew Pitcher: > On Thu, 05 Aug 2021 18:41:04 +0200, Arno Welzel wrote: > >> Torakiki: >> >>> json_encode it seems that, in the case of only one element with index = >>> 0, it returns an incorrect result. >>> >>> $array = []; >>> $array[0] = "Some text" >>> >>> it should return (in Firefox 90.0.2) >>> >>> {"0": "Some text"} >> >> Why? $array is still just an array with one scalar element. >> >>> and instead returns a string like >>> >>> ["Some text"] >> >> Which is valid json as well. This defines an array with one element. >> >> See: > > From that link, the OP's "unexpected" string Why? The string ["some text"] is a valid JSON array. Also see here: [...] > The OP changed the sequential array into a sparse array by > assigning additional elements asequentially: >>> $array[101] = "Some text 2" >>> $array[1234] = "Some text 3" > > Because of the "sparseness" of this object, it can't be > expressed as a JSON array, so json_encode() encoded the > input sparse array as a JSON object. Correct. -- Arno Welzel https://arnowelzel.de