Search code examples
jsonemacs

Emacs program to collapse Json to single line


I'm dealing with a file that has a list of single line json strings. To edit an individual json object, I found this tool: https://github.com/gongo/json-reformat. Now, I'm looking for the reverse operation: given a nicely formatted Json object, collapse it into a single string.

Emacs version: 24.5.1


Solution

  • Doesn't look like json-reformat comes with anything for that.

    Here's an interactive function that can do this:

    (defun json-to-single-line (beg end)
      "Collapse prettified json in region between BEG and END to a single line"
      (interactive "r")
      (if (use-region-p)
          (save-excursion
            (save-restriction
              (narrow-to-region beg end)
              (goto-char (point-min))
              (while (re-search-forward "\\s-+" nil t)
                (replace-match " "))))
        (print "This function operates on a region")))
    

    Just evaluate the function definition -> highlight the json snippet you want reformatted -> and call this function interactively