IT박스

JSON을 편집하는 Emacs 모드

itboxs 2020. 10. 22. 07:48
반응형

JSON을 편집하는 Emacs 모드


누구든지 JSON을 편집하는 데 좋은 Emacs 모드를 알고 있습니까? 내가 작업중인 앱은 JSON 기반 통신 프로토콜을 사용하며 데이터를 잘 들여 쓰고 구문 강조 표시하면 데이터를 파악하는 데 많은 도움이됩니다.


Emacs 용 Steve Yegge의 js2 모드를 사용해 보셨습니까 ?


+1 조쉬의 json 모드 -저에게 잘 맞습니다. 나는 추가했다

(defun beautify-json ()
  (interactive)
  (let ((b (if mark-active (min (point) (mark)) (point-min)))
        (e (if mark-active (max (point) (mark)) (point-max))))
    (shell-command-on-region b e
     "python -m json.tool" (current-buffer) t)))

(define-key json-mode-map (kbd "C-c C-f") 'beautify-json)

json-mode.el에 추가하여 쉘 명령 호출을 더 쉽게 만듭니다.

업데이트 : 유니 코드로 이것을 수행하기 위해 필요 / 욕망이있는 사람들은 여기 내 질문을 참조 하십시오 . 결론은 다음을 사용하는 것이 아닙니다.

python -m json.tool

당신은 사용하고 싶을 것입니다

python -c 'import sys,json; data=json.loads(sys.stdin.read()); print json.dumps(data,sort_keys=True,indent=4).decode("unicode_escape").encode("utf8","replace")'

이것은 원본 유니 코드 내용을 보존 할뿐만 아니라 JSON을 아름답게합니다.


js-mode는 json 파일에 대한 구문 강조 및 들여 쓰기를 지원합니다.

이것은 espresso-mode가 Emacs에 통합되고 js-mode로 이름이 변경된 Emacs 23.2 부터입니다.

확인 : http://www.nongnu.org/espresso/


가벼운 것을 원한다면 내가 함께 해킹 한이 메이저 모드를 시도해보세요 : https://github.com/joshwnj/json-mode

실제로 javascript-mode 위에 추가 구문 강조 표시에 불과하지만 제 목적을 위해 꽤 잘 작동하는 것으로 나타났습니다.

또 다른 일반적인 사용 사례는 JSON 파일의 형식을 자동으로 지정하는 것입니다 (예 : 공백으로 압축되어 있고 더 많은 가독성을 원하는 경우). 이렇게하려면 명령 줄 스크립트를 통해 버퍼를 파이핑하면됩니다. Cu M- |


js2 모드에 대한 해결 방법을 준비하여 오류없이 json 파일을 구문 분석합니다. 내 댓글에서 찾을 수 있습니다. http://code.google.com/p/js2-mode/issues/detail?id=50#c7

(나는 JF Sebastian 솔루션을 주석으로 게시하고 싶었지만 그렇게 할 수없는 것 같습니다 ( '주석 추가'링크 없음))


json.el by Edward O'Connor는 23.1 (2008) 이후 GNU Emacs의 일부입니다.

구문 하이 라이터는 아니지만 JSON 형식을 지정하는 데 유용한 기능이 있습니다.

M-x json-pretty-print-buffer RET

따라서 최신 버전의 Emacs가있는 경우 jq또는 python -m json.tool.


JSON은 YAML의 하위 집합이기 때문에 yaml-mode작동합니다 ( js-mode및과 비교하는 방법을 모르겠습니다 json-mode).

설치 (emacs에서) : M-x package-install yaml-mode.

협회 yaml-modeYAML과 JSON 파일에서와 ~/.emacs.d/init.el:

(add-to-list 'auto-mode-alist '("\\.yaml$" . yaml-mode))
(add-to-list 'auto-mode-alist '("\\.json$" . yaml-mode))

JSON은 에스프레소 모드에서 지원 됩니다.


js3 모드 : https://github.com/thomblake/js3-mode

js3 모드는 향상된 js2 모드입니다.

이 패키지는 package-list-packages 명령으로 설치할 수 있습니다.


나는 또한 Josh의 json-mode를 두 번째로 할 것이지만 추가로 flymake-json도 추천합니다. 구문 오류를 강조하는 데 도움이됩니다.

python -mjson.toolJSON 개체의 항목을 재정렬하기 때문에 사용하는 것을 좋아하지 않습니다 . 나는 (prog-indent-sexp)다시 들여 쓰기에 좋은 작품을 발견 하고 예쁜 인쇄 / 재 형식화를 위해 작품 jsonlint대신 사용python -mjson.toolbeautify-json

(eval-after-load "json-mode"
  '(progn
     (require 'flymake-json)
     ;; flymake-cursor displays error in minibuffer message area instead of requiring hover
     (require 'flymake-cursor)

     (add-hook 'json-mode-hook 'flymake-json-load)
     (define-key json-mode-map "\C-c\C-n" (function flymake-goto-next-error))
  )
)

Mariusz Nowak의 해결 방법을 확장 하여 자체적으로 주요 모드로 사용할 수 있도록했습니다. 단순히 모드를 유도하는 것 외에는 약간의 수정이 필요했습니다. Nowak의 작업에 실제로 필요한 유일한 변경 사항은 파일과 관련이 없거나 이름이으로 끝나지 않는 파일과 연결된 버퍼 .json를 JSON 으로 인식 할 수있는 기능이었습니다 .

다음은 강화 된 해결 방법입니다.

(make-variable-buffer-local 'js2-parse-as-json)

(defadvice js2-reparse (before json)
    (setq js2-buffer-file-name buffer-file-name))
(ad-activate 'js2-reparse)

(defadvice js2-parse-statement (around json)
    (if (and (= tt js2-LC)
           js2-buffer-file-name
           (or js2-parse-as-json
               (string-equal (substring js2-buffer-file-name -5) ".json"))
           (eq (+ (save-excursion
                    (goto-char (point-min))
                    (back-to-indentation)
                    (while (eolp)
                      (next-line)
                      (back-to-indentation))
                    (point)) 1) js2-ts-cursor))
      (setq ad-return-value (js2-parse-assign-expr))
        ad-do-it))
(ad-activate 'js2-parse-statement)

(define-derived-mode json-mode js2-mode "JSON"
  "Major mode for editing JSON data."
  :group 'json
  (setq js2-parse-as-json t)
  (js2-reparse t))

(add-to-list 'auto-mode-alist '("\\.json$" . json-mode))

이미 js2-mode를 사용하고 있다면 새로운 것을 설치할 필요가없고 (js2-mode는 이미 구문 검사를 수행하고, 외부 도구가 필요하지 않음)이 모드는 js2-mode를 상속하기 때문에 js-modeplus 보다 더 나은 옵션 일 수 있습니다. flymake-jsonjs-mode는 그렇지 않습니다.


또한 js2-mode를 권장합니다.

JSON stands for JavaScript Object Notation. It's not another language and it's even not a data container like yaml or xml are. JSON could be used as a data container if there's no function (or in this case we should say method) inside a JSON object, but it's not the primary goal of JSON :-)

var myJSObject = {
  attr: {foo: "bar", baz: ["quux", "truc", "pouet"]},
  fooAlert: function (num) {
    alert(this.attr.foo+' '+num);
  }
};
myJSObject.fooAlert(42);

참고URL : https://stackoverflow.com/questions/435847/emacs-mode-to-edit-json

반응형