3
0

More than 3 years have passed since last update.

JSONのkeyが数字の時

Posted at

扱うJSONデータ

こちらのデータを扱わせてもらいました。

qiita.json

[
  {
    "01": {
      "id": "01",
      "name": "北海道",
      "short": "北海道",
      "kana": "ホッカイドウ",
      "en": "hokkaido",
      "city": [
        { "citycode": "0010001", "city": "札幌市中央区" },
        { "citycode": "0010002", "city": "札幌市北区" },
        { "citycode": "0010003", "city": "札幌市東区" }, ...

なかなかデータを取り出せなかった原因

ブランケット記法を忘れていた

この書き方しか頭になくわけもわからず時間を浪費した。

qiita.js
import Jsondata from "./qiita.json";

  const data = Jsondata[0];
  console.log(data.01.id);//エラー
  // ドット記法は識別子の命名規則を満たす必要がある

ドット記法は簡単に言うと数字やハイフンが入ったものは扱えないからブラケット記法という[]の間に式を描く方法でないと変なエラーが出てくる

解決した書き方

ほかの言語ではこの書き方をよくするのになぜ思いつかなかったのか、

qiita.js
import Jsondata from "./qiita.json";

  const data = Jsondata[0];
  console.log(data["01"].id);//01
//ブランケット記法これが正解

3
0
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
3
0