1

I've a really big .json file with this structure:

[
  "9": {
    "id": 9,
    "chapter": 4
  },
  "4": {
    "id": 82,
    "chapter": 32
  },
]

I want to remove every quotation marks before the brackets. The file should looking like this:

[
  {
    "id": 9,
    "chapter": 4
  },
  {
    "id": 82,
    "chapter": 32
  },
]

I found a similar question here, but the result isn't that what I want.

Bassam
  • 497
  • 4
  • 12

1 Answers1

0

this step will remove keys; what are looking for( assuming no nested objects ) :

"\d+":\s*{ replace with '{'

this will remove latest ,if exist and turn last } to ]

},?\s*}$ replace with '}]'

optional step: this will remove latest ,if exist

},?\s*]$ replace with '}]'


check code snippet below for working example from your input to a valid json:

copy the pattern between // and paste it to vs-code find bar; (e.g. /},?\s*]$/ will be },?\s*]$) to be used in VSCode and the likewise for the replace

const input = `[
  "9": {
    "id": 9,
    "chapter": 4
  },
  "4": {
    "id": 82,
    "chapter": 32
  },
]`

const step1Find = /"\d+":\s*{/g;const step1Replace = '{'

//not needed anymore
//const step2Find = /^{/;const step2Replace = '['

//removing lastest comma if exists
const step3Find = /},?\s*]$/;const step3Replace = '}]'

let stringObject = input
.replace(step1Find,step1Replace)
.replace(step3Find,step3Replace)


console.log(JSON.parse(stringObject))
Mechanic
  • 5,015
  • 4
  • 15
  • 38