New FAMILUG

The PyMiers

Sunday 1 November 2020

Không cần jq nếu đã có python/ruby

jq trở thành công cụ "làm tất cả" với các sysadmin. Trong khi jq được dùng để "query JSON" - truy cập dữ liệu trong 1 đoạn JSON thì nó cũng được dùng để kiểm tra syntax của 1 đoạn JSON.

JQ là gì

$ whatis jq

jq (1)               - Command-line JSON processor
 

Photo by Thanh Soledas on Unsplash
 

Nhưng nếu máy đã có python/ruby, hay các ngôn ngữ trang bị sẵn stdlib JSON, sẽ không cần phải cài gì thêm cả:

File bad.json ví dụ, thử dùng mắt thường tìm xem nó sai ở đâu:

{
  "name": "@exercism/typescript",
  "description": "Exercism exercises in Typescript.",
  "private": true,
  "repository": {
    "type": "git",
    "url": "https://github.com/exercism/typescript"
  },
  "devDependencies": {
  },
}

Cả 3 công cụ sau đều trả về exit code khác 0 (tức không thành công, hay "bị  lỗi")

$ cat bad.json | jq ; echo $?
parse error: Expected another key-value pair at line 11, column 1
4
$ cat bad.json | python3 -m json.tool ; echo $?
Expecting property name enclosed in double quotes: line 11 column 1 (char 231)
1
$ cat bad.json | ruby -rjson -e 'JSON.load(STDIN)' ; echo $?
Traceback (most recent call last):
        3: from -e:1:in `<main>'
        2: from /home/vagrant/.rvm/rubies/ruby-2.7.0/lib/ruby/2.7.0/json/common.rb:335:in `load'
        1: from /home/vagrant/.rvm/rubies/ruby-2.7.0/lib/ruby/2.7.0/json/common.rb:156:in `parse'
/home/vagrant/.rvm/rubies/ruby-2.7.0/lib/ruby/2.7.0/json/common.rb:156:in `parse': 783: unexpected token at '{ (JSON::ParserError)
  "name": "@exercism/typescript",
  "description": "Exercism exercises in Typescript.",
  "private": true,
  "repository": {
    "type": "git",
    "url": "https://github.com/exercism/typescript"
  },
  "devDependencies": {
  },
}
'
1


Khi có trong tay những ngôn ngữ lập trình hạng xịn, trang bị tận răng như Python hay Ruby, bạn có thể làm rất rất nhiều thứ, trong 1 2 dòng, mà không cần cài thêm gì. Kiểm tra syntax JSON cũng không phải ngoại lệ.


Happy coding.

Tham khảo 

https://pp.pymi.vn/article/pycli/

Hết.

HVN at "học python tại PyMi" https://pymi.vn and https://www.familug.org 

No comments:

Post a Comment