String to json typescript

Typescript json string to json object in typescript

The exception is now caught and handled early: The generated code by quicktype for is: Introduction to TypeScript JSON parse To convert our string of JSON into an object, we can use the JSON parse method for it. As we already know, the JSON parse method is used to parse the string into an object in TypeScript.

Convert an Object Into a JSON String in TypeScript

This tutorial will introduce converting a TypeScript object to a JSON string.

Use the JSON.stringify() Method to Convert an Object Into a JSON String in TypeScript

In TypeScript, we will use the JSON.stringify() method to turn any object into a JSON string.

Below are some code examples to better understand how these methods work. Let’s consider the person object, which contains the person’s first and last name.

let person = < firstName:"Ibrahim", lastName:"Alvi" >; console.log(person) let jsonData = JSON.stringify(person); console.log(`The person object is : $ and it's JSON string is: $`); 

Use JSON.stringify() and JSON.parse() to Convert an Object Into a JSON String in TypeScript

Suppose we want to parse it back into the previous object. We use the JSON.parse() method to parse a JSON string to construct a TypeScript object described by the string.

The code below shows how object data can be saved to the local browser storage by turning it into a JSON string and how it can be retrieved and parsed.

We will use the JSON.stringify() and JSON.parse() methods.

// Storing data: const dataObj = < name: "Ibrahim", age: 31, city: "Karachi" >; const myJSON = JSON.stringify(dataObj); localStorage.setItem("testJSON", myJSON); // Retrieving data: let text = localStorage.getItem("testJSON"); let obj = JSON.parse(text); document.getElementById("dataid").innerHTML = obj.name; 

TypeScript JSON

Convert an Object Into a JSON String in TypeScript, Use the JSON.stringify() Method to Convert an Object Into a JSON String in TypeScript · Use JSON.stringify() and JSON.parse() to Convert an

Type-safely parsing JSON to a TypeScript Interface

Let’s say we’re working with a REST API that returns a JSON string representing a user. The JSON API agrees to a contract that it returns a string firstName , a string lastName and a number accountBalance . We model the user as an Interface in TypeScript as follow:

interface User  firstName: string; lastName: string; accountBalance: number; > 

The following code is sufficient if we always have the happy path :

const json = ' ' const user: User = JSON.parse(json) 

But things can go wrong on the API side. The json string returned could be:

const json ' ' const user: User = JSON.parse(json) console.log(user) 

The code does not blow up because accountBalance is now being treated as an any instead of a number . But this «forgiving» behavior leads to other problem downstream:

const balanceAfterInterest = user.accountBalance + user.accountBalance * 0.05 console.log(balanceAfterInterest) //1005 

The balanceAfterInterest is only supposed to be 105 . A better approach is to catch this problem early and handle it immediately and appropriately.

Head over to https://app.quicktype.io.

Paste the string to the left pane. Type User as the Name , and select JSON as the Source type .

Alt Text

In the box on the right, select TypeScript as the Language and make sure Verify JSON.parse results at runtime is turned-on. Quicktype will generate the resulting code with instruction on how to use it in the middle.

Alt Text

Now the following code can be much safer:

import  Convert, User > from "./user"; const json = ' '; try  const user = Convert.toUser(json); console.log(user); > catch (e)  console.log("Handle error", e); > 

The exception is now caught and handled early:

Alt Text

The generated code by quicktype for user.js is:

TypeScript JSON parse

Introduction to TypeScript JSON parse

To convert our string of JSON into an object, we can use the JSON parse method for it. As we know that the TypeScript is the subscript of JavaScript, so we can use its methods. JSON parse method is a JavaScript method but can be easily used in TypeScript like any other functions so far. To use the JSON parse method in TypeScript, we do not need to include any external library; for this, we can use it directly wherever we want.

As seen, it is used to parse the string into an object; also, it is available in the standard TypeScript library.

As you can see in the above syntax for JSON parse methods, it takes one parameter as the input param here and later converts it into the object in TypeScript.

How JSON parse Method Work in TypeScript?

As we already know, the JSON parse method is used to parse the string into an object in TypeScript. It is the method available in JavaScript. The string of JSON should follow the standard define by JSON like they should be in a key-value pair. Then only it will able to convert them into the specified object. In this section first we will see JSON parse method signature in detail see below;

Method Signature:

JSON.parse(text[, reviver]): This is the parse method’s signature defined by the javascript documentation. So as we can see, it takes up two parameters here. But the second parameter is optional. The first parameter would be the string of JSON into key-value pair in TypeScript.

1. Text

This parameter would be the string JSON.

Your JSON string should look like this. Then only it will parse them into the object; otherwise, we will receive exception at runtime in TypeScript.

2. Return Type

This parse method can return anything: string, array, object, null, number, boolean, etc.

3. Reviver

This is the second parameter of the JSON parse method, which is totally optional in TypeScript.

Now let’s see one sample example to understand its internal working.

const myjson = »;
const result = JSON.parse(myjson);
let mvalue = result.key2
console.log(mvalue);

In the above lines of code, as you can see, we are not using any external library to implement the JSON parse method in TypeScript; it is already available in the standard library. So first, we are trying to create the string of JSON. This should be in key-value pair. We named the string as ‘myjson’; after this, we are calling JSON.parse() method, and inside this, we are passing the variable that we have created.

So now it will test all the syntax and validate the passing JSON is correct or not. It should contain separated commons and also single quotes while using or preparing it. If the JSON is not correct, it will throw a runtime exception saying syntaxError while parsing the string. Immediately after this line, we have our object, which contains the json as an object, and their key and values can be access via their names. To access any object value, we can use the below syntax.

As you can see in the above lines of code, we can access the key-value by using its name only. So this makes the access oj object easy as well.

Example of TypeScript JSON parse

Given below is the example mentioned:

In this, we are trying to define several key and value inside the string json. After this, we converted it to an object in Typescript. After that, only we can access the object value from the JSON object available.

const myjson = »;
const result = JSON.parse(myjson);
let mvalue1 = result.key1
let mvalue2 = result.key2
let mvalue4 = result.key3
let mvalue5 = result.key4
let mvalue6 = result.key5
let mvalue7= result.key6
let mvalue8 = result.key7
let mvalue9 = result.key8
let mvalue10 = result.key9
let mvalue11 = result.key10
console.log( «first value is ::» +mvalue1);
console.log( «second value is ::» +mvalue2);
console.log( «fourth value is ::» +mvalue4);
console.log( «fifth value is ::» +mvalue5);
console.log( «six value is ::» +mvalue6);
console.log( «seven value is ::» +mvalue7);
console.log( «eight value is ::» +mvalue8);
console.log( «nine value is ::» +mvalue9);
console.log( «ten value is ::» +mvalue10);

TypeScript JSON parse

Rules and Regulation for JSON parse Method

There are some rules which needs to be taken while using the JSON parse method in TypeScript:

1. It takes two parameters, but the second parameter is the optional one, and the first one takes the input which needs to be parsed.

2. We should be very cautious while passing the string to parse inside the method.

  • The first one is it should not contain the single quotes inside the JSON string, which will make the JSON invalidate and hard to parse. As you can see in the below line of code, we are trying to wrap our key inside the ‘single quotes’ so it will make the string json invalidate.

3. Also, it should not contain the trailing commons in between the input.

  • ‘[300, 700, 800, ]’: Like this, it should not contain the commas; otherwise, it will make the input invalidate, and it will throw syntaxError while parsing it.
Conclusion

By using the JSON parse method, we can easily parse the JSON string. Also, it will make it easy to use the object and access its value. This can be useful when we have a response from the backend, which we want to parse to some object and access their values.

Final thoughts

This is a guide to TypeScript JSON parse. Here we discuss the introduction, how JSON parse method work in TypeScript? Example, rules and regulation. You may also have a look at the following articles to learn more –

Key of JSON Object as from function parameter, function toJSON( name: string, timestamp: number, x :number, y: number ): string < return JSON.

Источник

Typescript How to convert/parse String text to JSON Object

how to convert String to JSON Object in typescript?

The response returned from REST API or back servers in typescript/javascript is in the form of String JSON text, and developers must know how to convert it to JSON or class object.

Typescript is a superset of javascript with a type assertions feature. In javascript, we have used JSON.parse() method to convert to JSON. You can check here.

  • JSON.parse() method
  • String JSON text to Typescript class or interface object
  • String to an array of the class object example

Give a JSON text in String format — enclosed in single quotes.

How to Convert String contains text to JSON in typescript

JSON.parse() method is used to parse give string JSON text and convert to JSON Object. This is plain javascript which works in typescript

const employee = ''; console.log(typeof employee); let jsonObject = JSON.parse(employee); console.log(typeof jsonObject); //object console.log(jsonObject); // console.log(jsonObject.name); // Franc console.log(jsonObject.department); // sales
string object  name: 'Franc', department: 'sales' > Franc sales

The returned object is a plain object, which can hold any data.

The only concern with this approach is there is no use in typing to a class feature provided by typescript. Instead of a plain object, if you transfer to Typescript custom object, you have many advantages, static typing available at compilation that gives validation errors.
Let’s see an example of converting String JSON class object in typescript.

How to Convert/parse String to Typescript class object

Write a class or interface with all the fields of a JSON object with the type as follows.

interface Employee  name: string; department: string; salary: number; >

Here is the example code to convert to object class, The declared object of Employee type which holds parsed JSON object

var jsonObject: Employee = JSON.parse(emloyee); console.log(typeof jsonObject); //object console.log(jsonObject); // console.log(jsonObject.name); // Franc console.log(jsonObject.department); // sales
string object name: 'Franc', department: 'sales', salary: 5000 > Franc sales

How to Convert JSON string to array of objects/interfaces in typescript

Sometimes, the response contains an array of objects. First, Creates an Employee interface with required fields and map these fields with types that has returned data of an array.

Convert data returned from JSON.parse() to Array of Employee.

let response = '[, ]'; export interface Employee  id: string; name: string; > let responseObject: Employee[] = JSON.parse(response); console.log(response.length); //2

Conclusion

To Sum Up, Learned multiple ways to convert strings to json objects with examples.

Источник

Читайте также:  CODE
Оцените статью