Emacs程序将Json折叠为单行

时间:2016-10-04 20:54:59

标签: json emacs

我正在处理一个包含单行json字符串列表的文件。为了编辑单个json对象,我找到了这个工具:https://github.com/gongo/json-reformat。现在,我正在寻找相反的操作:给定一个格式良好的Json对象,将其折叠成一个字符串。

Emacs版本:24.5.1

3 个答案:

答案 0 :(得分:2)

看起来不像json-reformat那样。

这是一个可以执行此操作的交互式功能:

(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")))

只评估功能定义 - >突出显示要重新格式化的json片段 - >并以交互方式调用此函数

答案 1 :(得分:1)

对我来说(Emacs 25.1.1),使用接受的答案时,区域中的行没有连接。为了删除行结尾,我不得不扩展正则表达式:

(goto-char (point-min))
(while (re-search-forward "\\s-+\\|\n" nil t)
  (replace-match " "))))

答案 2 :(得分:0)

@AesopHimself和@Henschkowski的答案对我而言并不完全正确,因为它们要么没有消除换行符,要么在换行符和缩进缩合时没有在元素之间留下双倍空格。以下带有正则表达式的json-to-single-line函数对我有用:

(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 "[[:space:]\n]+" nil t)
            (replace-match " "))))
    (print "This function operates on a region")))