You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

在TS与NextJS中如何使用变量解析JSON数据

在TS与NextJS中如何使用变量解析JSON数据

嘿,看你是想在TypeScript和Next.js里用变量来解析指定的JSON内容对吧?我给你一步步讲清楚怎么实现,包你一看就会~

首先先把你要解析的JSON贴出来,方便对照:

{
    "Obj1" : {
         "Val1" : "Obj 1, Value 1",
         "Val2" : "Obj 1, Value 2",
         "Val3" : "Obj 1, Value 3"
    },
    "Obj2" : {
         "Val1" : "Obj 2, Value 1",
         "Val2" : "Obj 2, Value 2",
         "Val3" : "Obj 2, Value 3"
    }
}

第一步:给JSON定义TypeScript类型

TypeScript最香的就是类型检查了,先给这个JSON结构定义好类型,这样你用变量访问的时候不会写错键名,TS还会给你智能提示:

// 先定义每个子对象的类型
type ItemObj = {
  Val1: string;
  Val2: string;
  Val3: string;
};

// 再定义整个JSON的根类型,用索引签名支持变量作为key
type RootJson = {
  [key: string]: ItemObj;
};

第二步:准备JSON数据

不管你是直接写在代码里,还是从API/本地文件获取的JSON,都可以指定类型为我们刚才定义的RootJson:

const targetJson: RootJson = {
  "Obj1" : {
       "Val1" : "Obj 1, Value 1",
       "Val2" : "Obj 1, Value 2",
       "Val3" : "Obj 1, Value 3"
  },
  "Obj2" : {
       "Val1" : "Obj 2, Value 1",
       "Val2" : "Obj 2, Value 2",
       "Val3" : "Obj 2, Value 3"
  }
};

第三步:用变量访问JSON内容

这就是你要的核心操作啦!直接用变量作为key去访问JSON对象就行:

// 比如你要访问Obj1,把它存在变量`currentKey`里
const currentKey = "Obj1";
// 用变量`currentKey`获取对应的子对象
const currentItem = targetJson[currentKey];

// 然后就可以拿到里面的值了
console.log(currentItem.Val1); // 输出 "Obj 1, Value 1"
console.log(currentItem.Val2); // 输出 "Obj 1, Value 2"

Next.js里的实战例子

如果是在Next.js页面里用,比如从服务端获取数据再在组件里用变量解析,我给你写个完整的页面例子:

// pages/json-demo.tsx
import type { GetStaticProps } from 'next';

// 先定义好类型
type ItemObj = {
  Val1: string;
  Val2: string;
  Val3: string;
};

type RootJson = {
  [key: string]: ItemObj;
};

// 页面接收的props类型
type PageProps = {
  jsonData: RootJson;
};

export default function JsonDemoPage({ jsonData }: PageProps) {
  // 这里可以根据业务逻辑动态设置变量,比如从URL参数、状态里取
  const activeKey = "Obj2";
  const selectedItem = jsonData[activeKey];

  // 保险起见,加个判断避免key不存在导致报错
  if (!selectedItem) {
    return <div>找不到对应的数据哦</div>;
  }

  return (
    <div className="p-4">
      <h2 className="text-xl font-bold mb-2">{activeKey} 的详情</h2>
      <ul className="space-y-1">
        <li>Val1: {selectedItem.Val1}</li>
        <li>Val2: {selectedItem.Val2}</li>
        <li>Val3: {selectedItem.Val3}</li>
      </ul>
    </div>
  );
}

// 从服务端获取JSON数据(也可以换成getServerSideProps或者客户端请求)
export const getStaticProps: GetStaticProps<PageProps> = async () => {
  // 这里模拟获取JSON,实际可以是fetch API请求本地文件或外部接口
  const jsonData: RootJson = {
    "Obj1" : {
         "Val1" : "Obj 1, Value 1",
         "Val2" : "Obj 1, Value 2",
         "Val3" : "Obj 1, Value 3"
    },
    "Obj2" : {
         "Val1" : "Obj 2, Value 1",
         "Val2" : "Obj 2, Value 2",
         "Val3" : "Obj 2, Value 3"
    }
  };

  return {
    props: { jsonData },
  };
};

小提醒

如果你的变量对应的key可能不存在于JSON里,一定要加个存在性判断,不然会出现Cannot read properties of undefined的错误,就像上面例子里的if (!selectedItem)那样处理~

备注:内容来源于stack exchange,提问作者Skj0nes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.13 17:04:36