Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wrap JSON field names in quotes using vim search and replace

Tags:

regex

vim

I have a simple json file that isn't well formatted it looks like:

{ ID: '092558667',  
  NAME: 'Store Made',  
  PARENT_CATEGORY_ID: '692558669',  
  INCLUDED_IN_NET_SALES: '1' }  

All I need to do is wrap the field names in double quotes. In vim the closest I have gotten is to wrap the field name and the colon in quotes - obviously I need to figure out how to get the string without the colon wrapped. Here's what I am trying:

:%s/[A-Z_]*:/"&"

If I leave the colon out of the query the whole file ends up being selected.

like image 451
akronymn Avatar asked Sep 30 '13 16:09

akronymn


2 Answers

You can use capture groups:

%s/\([A-Z_]*\):/"\1":/

To handle already quoted keys properly:

%s/"\?\([A-Z_]*\)"\?:/"\1":/
like image 80
Felix Kling Avatar answered Sep 28 '22 02:09

Felix Kling


Ok, with the information above I ended up with this:

:%s/[ \t]\([A-Za-z_].*\):/"\1":/
  • it supports upper- and lowercase chars
  • it skips already quoted fields

Since this can be considered a completion, I mapped it to a vim completion shortcut ctrl-x ctrl-j in .vimrc (they all start with ctrl-x ) :

:noremap <C-x><C-j> :%s/[ \t]\([A-Za-z_].*\):/"\1":/<CR>
like image 43
coderofsalvation Avatar answered Sep 28 '22 03:09

coderofsalvation