LoginSignup
4
5

More than 5 years have passed since last update.

日本語を含む JSONP を jq する

Posted at

JSONP を jq コマンドで確認したいと思い、調べてたら下記の Wiki を発見し、
試してみたんですがどうやら日本語を含む JSONP だと動かない。。

日本語を含まない JSONP の場合

$ echo 'callback({"foo":"bar"});' | jq -R '.[1+index("("): rindex(")")] | fromjson'
{
  "foo": "bar"
}

意図したとおりの結果が返ってくる。

日本語を含む JSON の場合

$ echo 'callback({"foo":"ばあ"});' | jq -R '.[1+index("("): rindex(")")] | fromjson'
jq: error (at <stdin>:1): Invalid numeric literal at EOF at line 1, column 18 (while parsing '{"foo":"ばあ"});')

rindex 関数が byte 数で計算してるようで後ろの ); が消されない。。

解決策

下記のように ruby で JSONP のコールバック関数部分を除去してから jq に渡す jqp という名前のエイリアスを作成。

$ alias jqp="ruby -e 'print gets.gsub(/^[a-zA-Z0-9_ \.]*\(|\);?$/, \"\")' | jq"`

※除去する正規表現部分はこれだとまだ不十分かも?

jqp エイリアスの実行結果

$ echo 'callback({"foo":"bar"});' | jqp .
{
  "foo": "bar"
}
4
5
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
5