Skip to content
The Chat Archive
Hugging Face Space: huggingfaceh4-starchat-playground ShareLM (browser-extension contributions)

How to decode JSON into a typescript object

  1. User

    How to decode JSON into a typescript object

  2. Assistant
    
    
    
    const json = '{"name": "John", "age":30, "city":"New York"}';
    // Convert it to a JavaScript Object first
    let obj = JSON.parse(json); 
    
    // Then convert it back to a strongly typed one using the following syntax (this will work for any valid JSON)
    let person : { name: string; age: number; city:string } = <any>obj; // or just cast as Person type if you have defined interface/class Person
    console.log(person.name); // John
    console.log(person.age); // 30
    console.log(person.city); // NewYork