vimtricks.wiki Concise Vim tricks, one at a time.

How do I create a macro to convert a value to a JSON key-value pair?

Answer

qaI"<Esc>A": "",<Esc>jq

Explanation

This macro transforms a plain word into a JSON key-value pair format, useful for converting lists of field names into JSON structure.

How it works

  1. qa — start recording
  2. I" — insert opening quote at line start
  3. <Esc> — back to normal mode
  4. A": "", — append key-value syntax at end
  5. <Esc>j — back to normal, move down
  6. q — stop recording

Example

name
age
email

After running on each line:

"name": "",
"age": "",
"email": "",

Tips

  • Modify for different formats (YAML, TOML, etc.)
  • Use {count}@a to process multiple lines
  • Customize the value placeholder as needed
  • Combine with :g/./normal @a for non-blank lines only

Next

How do you yank a single word into a named register?