Home > database >  vim: how to format wrong json
vim: how to format wrong json

Time:11-29

I need to copy data from mongodb cli, for example,

{ "_id" : "95945f53-ae0d-4337-b5cc-af44e230b964", "field1" : "value1", "field2" : "value2", "field3" : "value3", "field4" : false, "createdTime" : NumberLong("1629562382798"), "updatedTime" : NumberLong("1629562382798")}

and format it like this:

{
   "_id":"95945f53-ae0d-4337-b5cc-af44e230b964",
   "field1":"value1",
   "field2":"value2",
   "field3":"value3",
   "field4":false,
   "createdTime":NumberLong("1629562382798"),
   "updatedTime":NumberLong("1629562382798")
}

I would like to be able to format it in vim or nvim editor. I found a few ways how to do it:

  1. :%!jq returns jq: error: syntax error, unexpected '/', expecting $end (Unix shell quoting issues?) at <top-level>, line 1:
  2. :%!python -m json.tool returns No JSON object could be decoded
  3. https://github.com/tpope/vim-jdaddy says invalid json so all of them requires valid json.

When I format it in vscode with embedded tool (right click then choose "format code") it works fine. Is there a way do the same in vim or nvim?

CodePudding user response:

You can insert line breaks by replacing the commas:

:%s/,/,^M/g

and then add the indentations and the two remaining line breaks for the opening and closing braces manually.

(type Ctrl-v-Enter for ^M)

Adding indentation can for example be done by selecting all lines in visual line mode (Shift-v) and then pressing >.

CodePudding user response:

I came up with this:

:%s/,/,\r\t/g | s/}/\r&
  • Related