bspckl
bspckl

Reputation: 197

VIM: swap json values within double quotes

I need to swap tag and value in a json file on multiple lines using VIM editor.

ex: this:

{"value":"PAE","tag":"project:aerospace;id:3364"} {"value":"#cybersecurity","tag":"project:aerospace;id:3178"} {"value":"Boeing","tag":"project:aerospace;id:3342"} {"value":"Airbus","tag":"project:aerospace;id:3335"}

needs to be:

{"tag":"project:aerospace;id:3364","value":"PAE"} {"tag":"project:aerospace;id:3178","value":"#cybersecurity"} {"tag":"project:aerospace;id:3342","value":"Boeing"} {"tag":"project:aerospace;id:3335","value":"Airbus"}

I have gotten as far as :%s/tag/value/g (using a temp) for the tag and value, but I need to know how to swap either everything within the 2nd and 4th double quotes or everything before and after the comma.

Upvotes: 1

Views: 144

Answers (4)

Mitchell Byrd
Mitchell Byrd

Reputation: 73

The following regex works for me:

%s/{("value":".*?"),("tag":".*?")}/{\2,\1}/g

See it working here: https://regex101.com/r/xR7lR0/1

Upvotes: 0

Kent
Kent

Reputation: 195059

%norm! f,xdT{f}i,^R"

In above cmd, ^R you press ctrl-v ctrl-r

Upvotes: 4

Chris
Chris

Reputation: 391

:%s/{\([^,]*\),\([^,]*\)}/{\2,\1}/

Something like that?

Upvotes: 1

moopet
moopet

Reputation: 6175

This should do the trick:

%s/\v("value":"[^"]+"),("tag":"[^"]+")/\2,\1/

Uses "very magic" to make things easier, saves the two groups and replaces them using back-references.

Upvotes: 0

Related Questions