LoginSignup
22
16

More than 5 years have passed since last update.

【JavaScript】ネストされたJSONデータの値取得について

Last updated at Posted at 2018-09-18

経緯

2ヶ月くらい前、JSONデータを全て抜き出して、値を取り出さなければならない依頼がありました(何故かは伏せておきます…)。

一次元ならまだしも、二次元配列の処理となるとちょっと骨が折れます。
どうしようかと考えたのですが、再帰的に動く処理を使って対応することにしました。

コード

以下、対応に対して組んだJSです。

JsonDetaileOutput.js
// Jsonの中身
var jsons ={
    "masterNumber": 10000,
    "code": "m-001",
    "customerData": {
        "name": "Jiro",
        "age": 45
    },
    "Address": [{
        "name": "testAreport",
        "email": "tA@sample.co.jp"
    }],
    "items": [{
        "itemId": "item01",
        "itemName": "商品01"
        },
        {
        "itemId": "item02",
        "itemName": "商品02"
        },
        {
        "itemId": "item03",
        "itemName": "商品03"
    }]
};

// jsonを分解する処理
function getValue(obj) {
    if (typeof obj === 'object') {
        var strValue = '';
        for (key in obj) {
            strValue += getValue(obj[key]);
        }
        return strValue;
    } else {
        return obj;
    }
}

// 出力結果
console.log(getValue(jsons));

オブジェクトの中を検索して、更にオブジェクトがあった場合はgetValueを再度呼んでその中身をチェックして値を読み出しています。

実証

実行した時の出力結果です。
実行はnode.jsで行っております。

$ node JsonDetaileOutput.js
10000m-001Jiro45testAreporttA@sample.co.jpitem01商品01item02商品02item03商品03

ちゃんと出力されました。
後は、このデータを煮るなり焼くなりして加工するのみです。

おわりに

これで終わりになります。
同じような問題に苦しむ方の手助けとなりましたら幸いです。

実は、以前に質問サイトに投稿していた内容がありまして、こちらが元ネタとなっております。
https://teratail.com/questions/136359

22
16
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
22
16