IBM Watson APIの返却値(JSON)をPythonでパースする方法

Taiji
Taiji
Nov 3 · 5 min read

はじめに

今回はWatsonのVisual Recognition(以後VR)のAPIを利用した際に返却されるJSON形式の結果値をPythonで扱う方法を書きたいと思います。

JSONのパース自体は言語問わずほとんどやってることは変わらないですので内容は基本的なものになってます。
私自身はPythonは全く書かないのですが、ハッカソンなどではPythonを使われる方も多く、技術サポートするにあたり自分の頭の中を整理する意味も含めまとめようと思いました。

JSONサンプルデータ

以下がWatson VRの返却値サンプルです。watson_res.json という名前で作成しておきました。

watson_res.json
{
“images”: [
{
“classifiers”: [
{
“classifier_id”: “roundPlusBanana_1758279329”,
“name”: “roundPlusBanana”,
“classes”: [
{
“class”: “fruit”,
“score”: 0.788
},
{
“class”: “olive color”,
“score”: 0.973
},
{
“class”: “lemon yellow color”,
“score”: 0.789
}
]
}
],
“image”: “fruitbowl.jpg”
}
],
“images_processed”: 1,
“custom_classes”: 6
}

ここでは説明のため、わかりやすくJSONはファイルで用意し、

json_file = open(‘watson_res.json’, ‘r’)

としてJSONを読み込んでいますが、実際のAPIコールのときはAPIの戻り値をJSONオブジェクトとして扱って頂ければOKです。

JSONデータの分解

では、まずは”images”の下をまるっと取り出してみましょう。

import jsonjson_file = open(‘watson_res.json’, ‘r’)
json_object = json.load(json_file)
print(json.dumps(json_object["images"]))

まあ、かんたんですよね。きれいに取り出せました。
では次に"classifiers"の下を取り出してみましょう。

import jsonjson_file = open(‘watson_res.json’, ‘r’)
json_object = json.load(json_file)
print(json.dumps(json_object["images"][0]["classifiers"]))

“images”の配列0番目の"classifiers"を指定すればOKです。問題なく取れましたね。
では次は、"classes"の要素としてフルーツとオリーブ色とレモンイエローが3つの配列で入ったものがありますので、これの1つ目を取り出してみましょう。

import jsonjson_file = open(‘watson_res.json’, ‘r’)
json_object = json.load(json_file)
print(json.dumps(json_object[“images”][0][“classifiers”][0][“classes”][0]))

こちらも問題なく取れました。
最後に、スコアとクラスのそれぞれの値を取り出してみたいと思います。

import jsonjson_file = open(‘watson_res.json’, ‘r’)
json_object = json.load(json_file)
print(json.dumps(json_object[“images”][0][“classifiers”][0][“classes”][0][“score”]))
print(json.dumps(json_object[“images”][0][“classifiers”][0][“classes”][0][“class”]))

はい、こんな感じです。

ネストが深くなった、一見複雑そうなJSONであっても、基本的にはハッシュと配列の組み合わせだけですので、頭がこんがらかった時には先頭から一つづつ整理して値を取り出してみると良いでしょう。

ではでは。

お知らせ

クレジットカード不要でいつまででもお使い頂けるIBM Cloudアカウントはこちらから取得できます。これを機に是非お試しください!

https://ibm.biz/Bdz3bC

Taiji

Written by

Taiji

IBM Developer Advocate🥑. Swift, Node-RED/Node.js Expert. ここでの発言・記事は個人の見解であり、所属する組織等の公式見解ではありません。

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade