简体   繁体   中英

how to convert json string back to an object in Angular 8

I converted this object into JSON string. values of subject1, subject2, subject 3 are coming from input fields in angular frontend

subject = {
    "subject1": "A",
    "subject2": "B",
    "subject3": "C"
}

and now I have a JSON string like this,

const subjects = {"subject1": "A", "subject2": "B","subject3":"c"}

Like this, I saved this as a JSON string in DB. In another place, I wanted to access this string as an object as previously I made. to output these subjects separately as same as It gets as an object.

example:- First input box - subject1 value as A , Second input box - subject2 value as B

How can I put them back again like separate values into separate variables or any other way to separate them and put back into the text fields?

I just tried to get that JSON string and tried to access subject1 like subject1 = subjects.subject1 like that I can put subject1 in relevant text field. But that doesn't work. I checked previous questions like this. But they didn't answer my question. How can I solve this?

You can do it with JSON.parse .

  const obj = JSON.parse(subjects);
  console.log(obj.subject1);  // "A"

You can use destructuring assignment :

The destructuring assignment syntax is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables.

 const subject = { "subject1": "A", "subject2": "B", "subject3": "C" } const {subject1,subject2,subject3} = subject; console.log(subject1); console.log(subject2); console.log(subject3);

You can find more about destructuring assignment here

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM