LoginSignup

エンジニアとしての市場価値を測りませんか?PR

企業からあなたに合ったオリジナルのスカウトを受け取って、市場価値を測りましょう

0
0

JSON オブジェクトの中に空文字のキーや値があるかどうかを判定する

Posted at

JSON オブジェクトの中に空文字のキーや値があるかどうかを判定する関数を作りました。(便利な関数ややり方があるかどうか探してみても見つからなかった。。。)

再帰処理を入れているので、json の階層が深くなった際のデータにも対応している(はず)

json の中身を見ていって、key または value に空文字が一箇所でもセットされていると true を返します。(それ以外の場合は false が返ります。)

// 入力用 JSON オブジェクト
const inputJSON = {
  key1: "value1",
  key2: 12,
  key3: true,
  key4: {
    key4_1: "valueA",
    key4_2: "", // これがあると true が返る
    key4_3: {},
    "": "", // これがあると true が返る
    "": "xxx", // これがあると true が返る
  },
  key5: '""',
  key6: {},
  key7: [],
  key8: "", // これがあると true が返る
  key9: null,
  '""': "valueY",
  "": "valueX", // これがあると true が返る
  "": "", // これがあると true が返る
};

// 判定関数
const existEmptyKeyValue = (jsn) => {
  try {
    JSON.parse(JSON.stringify(jsn));
  } catch (err) {
    throw new Error(`invalid json format. err: ${err}`);
  }

  if (Object.keys(jsn).length === 0) {
    return false;
  }

  for (const key of Object.keys(jsn)) {
    const value = jsn[key];
    if (key === "") {
      return true;
    }
    if (value === "") {
      return true;
    }
    if (typeof value === "object" && value !== null) {
      if (existEmptyKeyValue(value)) {
        return true;
      }
    }
  }

  return false;
};

// 動作確認
console.log(existEmptyKeyValue(inputJSON));

あとはテストコードをしっかり書けるとより安全なコードになるかなと思います。

あとがき

上記を実装していて、typeof null は object になることを知りました。

console.log(typeof null); // object
0
0
1

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
suisuisuuui

@suisuisuuui

IT エンジニアです。趣味は休日の昼間からビールを飲むこと。 サーバサイドもフロントエンドもやります。ゆるーく生きてます。そろそろ車中泊で日本一周したい。 Golang/TypeScript/Svelte

Comments

oswe99489
@oswe99489

オブジェクトの中身を実際にループさせながら調べていかなくても、JSON.stringify()が返した文字列を正規表現でチェックすれば済むかと思います。

const existEmptyKeyValue = obj => /[{,:]""/.test(JSON.stringify(obj));
0

Let's comment your feelings that are more than good

Being held Article posting campaign

paiza×Qiita記事投稿キャンペーン「プログラミング問題をやってみて書いたコードを投稿しよう!」

~
View details
0
0

Login to continue?

Login or Sign up with social account

Login or Sign up with your email address