小塌客

石头的博客

Category "ruby"

json_formatter

最近一直在用sinatra做API, OAuth2的东西, 调试用的curl, 数据的返回格式是json, 默认情况下一对一对字符串是直接在console输出出来的,不方便查看,像这样:
{"accounts":[{"name":null,"id":"4ea060742c76682ab800a807","api_url":"https://api-dev.example.com/partners/4ea05b812c76682ab800a0b0/accounts/4ea060742c76682ab800a807","email":"skidave32289@gmail.com"},{"name":null,"id":"4ea06b5e2c76682aa6002ac5","api_url":"https://api-dev.example.com/partners/4ea05b812c76682ab800a0b0/accounts/4ea06b5e2c76682aa6002ac5","email":"skidave32289+20@gmail.com"},{"name":null,"id":"4ea071862c766848c3000055","api_url":"https://api-dev.example.com/partners/4ea05b812c76682ab800a0b0/accounts/4ea071862c766848c3000055","email":"skidave32289+21@gmail.com"},{"name":null,"id":"4ea075e02c766848c8000ae5","api_url":"https://api-dev.example.com/partners/4ea05b812c76682ab800a0b0/accounts/4ea075e02c766848c8000ae5","email":"skidave32289+22@gmail.com"}]}
今天在rubyflow上看到一个不错的工具gem: json_formatter, 直接gem install后,就可以在命令行用了:
#curl -H 'EXAMPLE-API-KEY: b60b5400dd6f012eg16c12313b0ecdxc2' "https://api-dev.example.com/partners/4ea05b812c76682ab800a0b0/accounts?per_page=100" | json_formatter 
  % Total    % Received % Xferd  Average Speed   Time    Time     Time  Current
                                 Dload  Upload   Total   Spent    Left  Speed
100  5812  100  5812    0     0   3358      0  0:00:01  0:00:01 --:--:-- 11049
{
  "accounts": [
    {
      "name": null,
      "id": "4ea060742c76682ab800a807",
      "email": "skidave32289@gmail.com",
      "api_url": "https://api-dev.example.com/partners/4ea05b812c76682ab800a0b0/accounts/4ea060742c76682ab800a807"
    },
    {
      "name": null,
      "id": "4ea06b5e2c76682aa6002ac5",
      "email": "skidave32289+20@gmail.com",
      "api_url": "https://api-dev.example.com/partners/4ea05b812c76682ab800a0b0/accounts/4ea06b5e2c76682aa6002ac5"
    },
    {
      "name": null,
      "id": "4ea071862c766848c3000055",
      "email": "skidave32289+21@gmail.com",
      "api_url": "https://api-dev.example.com/partners/4ea05b812c76682ab800a0b0/accounts/4ea071862c766848c3000055"
    }
  ]
}

#也可以直接输入字符串
#json_formatter "{}"

ps: 关于curl
上面提到了curl,就再多说一点吧,在用curl进行POST请求添加数据时需要注意, 使用 -d "name=value" 的方法是不会自动给value进行编码(url escape)的, 如果想让curl给数据进行escape需要使用 --data-urlencode 选项:
#curl -d "site=www.ccok.me" --data-urlencode "email=li+lei.hand-some2@yottaa.com" -H 'EXAMPLE-API-KEY: b60b5400dd6f012ec57c123112b0ecda2' "https://api-dev.example.com/partners/4ea05b812c76682ab800a0b0/accounts"