Home About Contact
JSON

JSONPath, XML における XPath があるように JSON には JSONPath がある

JSONPath XPath for JSON というのがあることを知る。 JSONPath を Node.js で使える実装のひとつが jsonpath 。 これを試した。

使うには、次のようにするだけ。

$ npm install jsonpath

次のような pokemons.json があったとして:

{
  "items": [
    {
      "id": 1000,
      "name": "Pikachu"
    },
    {
      "id": 1001,
      "name": "Metapod"
    },
    {
      "id": 1002,
      "name": "Piplup"
    }
  ]
}

これの id リストを得るには:

const fs = require('fs');    
var jsonpath = require('jsonpath');

const filePath = 'pokemons.json';
const text = fs.readFileSync(filePath, 'utf8');  

const obj = JSON.parse(text);
var ids = jsonpath.query(obj.items, '$..id');
console.log(ids); // => [1000, 1001, 1002]

$..id と指定するとそれが得られる。

実行環境

$ node --version
v22.13.1

$ npm --version
10.9.2

jsonpathを使わないで記述するには:

const fs = require('fs');    

const filePath = 'pokemons.json';
const text = fs.readFileSync(filePath, 'utf8');  

const obj = JSON.parse(text);
const ids = obj.items.map((item)=> item.id);
console.log(ids); // => [1000, 1001, 1002]

obj.items.map((item)=> item.id) と書くだけです。

あるJSON文字列から特定の情報だけを抜き出したい。 しかし、ユーザーは JavaScript をいっさい書かないで済ませたい。 というような状況では威力を発揮しそうです。 たとえば、Google App Script から呼び出す API とか。