josdejong / svelte-jsoneditor

A web-based tool to view, edit, format, repair, query, transform, and validate JSON
https://jsoneditoronline.org
Other
816 stars 108 forks source link

Parsing JSON with duplicate keys in onChange throws "RangeError: Selection points outside of document" #331

Closed ZRui98 closed 7 months ago

ZRui98 commented 8 months ago

Hi, I ran into this with svelte + svelte-jsoneditor v0.17.9. When pasting in JSON with duplicate keys, this error from codemirror gets thrown: Uncaught (in promise) RangeError: Selection points outside of document. I noticed this started occurring on v0.17.9, but was not present on v0.17.8. Minimal example to reproduce: https://www.sveltelab.dev/8u8l783v8eij2b1 To reproduce, paste

{"a":"a", "a":"b"}

into the editor. An error should be thrown in the console log. Thanks.

josdejong commented 8 months ago

Thanks for reporting.

I can reproduce the same error with the following contents:

{"a":"a"                }

The issue occurs when you replace the JSON text contents with something that was shorter than the original text during in the onChange callback. In your case, you run JSON.parse followed by a JSON.stringify($json, null, 2). This loses the original white spacing and duplicates.

We should look into why this error is thrown, that should not happen.

At the same time: you should not run this JSON.parse and JSON.stringify loop in the first place. That makes it impossible to edit the contents in a "normal" way, since the editor is normalizing all white-spacing whilst you're typing. For example: initially, the editor in your example contains {}. When I put the cursor between the { and }, and press enter to start typing a new property on the second line, the contents is reset again to {}, making it literally impossible to insert something.

Instead, you can just keep the content in your state, and only as soon as you're going to save the document or so, run a JSON.parse on the contents.

josdejong commented 7 months ago

Fixed now in v0.18.2