จัดโค้ด JSON ใน Vim

Armno's avatar image
Published on January 25th, 2016
By Armno P.

การ format file JSON (จัดให้เป็นระเบียบ, uncompressed, prettify) ปกติเป็นงานที่ผมไม่ได้ทำใน Vim ต้องพึ่ง editor ตัวอื่น (เพราะไม่เคยรู้วิธีการ) แต่ด้วยความสงสัยก็เลยลองค้นหาวิธีในเน็ตดู ก็พบว่ามีหลายทางให้เลือก

สมมุติว่าผมมีไฟล์ JSON ที่ถูก compressed มาไว้แบบนี้

[{"model":"x-e1","brand":"fuji","type":"mirrorless"},{"model":"d60","brand":"nikon","type":"dslr"}]

ต้องการจะ expand/prettify มันออกด้วย Vim จะต้องทำยังไง

วิธีที่ 1: ใช้ json.tool ใน Python

ในเครื่องถ้าลง Python ไว้ก็จะมี module ที่ชื่อว่า json.tool ใช้ format JSON ผ่าน command line ได้

$ python -m json.tool <FILENAME>

# หรือ
$ cat <FILENAME> | pythone -m json.tool

ซึ่งใน Vim เราสามารถ execute command line ได้จาก Ex mode (กด : หรือ Q ใน Normal mode) ดูรายละเอียดของ command นี้ได้ที่ Pretty printing JSON in Vim ได้เลยจ้า

:%!python -m json.tool

ก็จะได้ JSON ที่ format แล้ว

[
    {
        "brand": "fuji",
        "model": "x-e1",
        "type": "mirrorless"
    },
    {
        "brand": "nikon",
        "model": "d60",
        "type": "dslr"
    }
]

แต่มีข้อสังเกตก็คือ

  1. แต่ละ property ของ object ถูกเรียงใหม่ตามตัวอักษร ในไฟล์ตัวอย่างคือ property brand ถูกเลื่อนขึ้นมาอยู่ก่อน model
  2. ไม่สามารถกำหนดจำนวน space ได้ จะเป็น 4 space ตลอด

ผมก็เลยลองหาวิธีอื่นดู เจอ Node module ที่ชื่อว่า json

วิธีที่ 2: ใช้ json Node module

ขั้นแรกต้องลง json Node module แบบ global ก่อน เพื่อให้เราสามารถใช้ command json ได้

$ npm install -g json

ใช้งานใน Vim จาก Ex mode เหมือนเดิม

:%!json

ก็ได้ JSON ที่ format แล้วแบบนี้

[
  {
    "model": "x-e1",
    "brand": "fuji",
    "type": "mirrorless"
  },
  {
    "model": "d60",
    "brand": "nikon",
    "type": "dslr"
  }
]

สังเกตว่าลำดับของแต่ละ property ยังเหมือนเดิม ส่วนจำนวน space เป็นค่า default คือ 2 space ในการ indent เราสามารถทำหนดได้ด้วยการส่ง argument ให้ json command

:%!json -2         # 2 spaces
:%!json -4         # 4 spaces
:%!json -o json-7  # 7 spaces, กรณีที่ไม่ใช่ 2 หรือ 4

3. ใช้ sourcebeautify.vim

sourcebeautify.vim เป็น plugin ของ Vim ใช้ format code อย่างอื่นนอกจาก JSON ได้ด้วย (HTML, JavaScript, CSS, JSON, XML, MySQL) แต่ผมยังไม่ได้ใช้เยอะขนาดนั้น เลยยังไม่ได้ลอง แต่ก็เป็นอีกทางเลือกนึงที่น่าจะใช้ได้ครับ

ใครมีวิธี format JSON ใน Vim วิธีอื่นๆ แนะนำกันได้นะ

Sources

Related posts