簡體   English   中英

Typescript JSON 動態接口

[英]Typescript JSON to interface dynamically

我對 typescript 很陌生,我想將下面的 JSON 轉換為接口/類型,但user1鍵是動態的,可能有所不同,但 Z0ECD11C1D7A287401D148A23BBD7A2F8 內部的鍵將相同。

{
  "code": 200,
  "status": "success",
  "data": {
    "user1": {
       "firstName": "John",
       "lastName": "Smith",
       "age": 25
     }
  }
}

到目前為止,我有以下內容。 是否可以在 Root 接口中將數據轉換為 map,因為這就是我在 golang 中的操作方式。

export interface Root {
  code: number
  status: string
  data: Data
}

export interface Data {
    [key: string]: User
}

export interface User {
    firstName: string
    lastName: string
    age: number
}

export const sendRequest = (url: string): Root => {
  const [data,setData]=useState([]);
  const getData=()=>{
    fetch(url
    ,{
      headers : { 
        'Content-Type': 'application/json',
        'Accept': 'application/json'
       }
    }
    )
      .then(function(response){
        return response.json();
      })
      .then(function(myJson) {
        setData(myJson)
      });
  }
  useEffect(()=>{
    getData()
  },[])
  return JSON.parse(JSON.stringify(data));
}

const user = sendRequest(host + path) 

console.log(user.data?.[0]) 

您可以使用索引簽名:

export interface Root {
    code: number
    status: string
    data: Data
}

export interface Data {
    [key: string]: User
}

export interface User {
    firstName: string
    lastName: string
    age: number
}

這是我目前使用的方式,但它不起作用

export interface Root {
    code: number
    status: string
    data: Data
}

export interface Data {
    [key: string]: User
}

export interface User {
    firstName: string
    lastName: string
    age: number
}

export const sendRequest = (url: string): Root => {
  const [data,setData]=useState([]);
  const getData=()=>{
    fetch(url
    ,{
      headers : { 
        'Content-Type': 'application/json',
        'Accept': 'application/json'
       }
    }
    )
      .then(function(response){
        return response.json();
      })
      .then(function(myJson) {
        setData(myJson)
      });
  }
  useEffect(()=>{
    getData()
  },[])
  return JSON.parse(JSON.stringify(data));
}

const user = sendRequest(host + path) 

console.log(user.data?.[0]) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM