0

The below (string) return array of JSON dynamically in shape of (string):

let test = '{ "UserDepartmentName": { "OldValue":"Abc123", "NewValue": "Abc123456"  }, "ModifiedDate": { "OldValue":"5/19/2021 12:37:22 PM", "NewValue": "5/24/2021 4:12:21 PM"  } }'
  }'
console.log(test)

I need to convert this (string) to (array of JSON) to extract the data like below:

{
   "UserDepartmentName":{
      "OldValue":"Abc123",
      "NewValue":"Abc123456"
   },
   "ModifiedDate":{
      "OldValue":"5/19/2021 12:37:22 PM",
      "NewValue":"5/24/2021 4:12:21 PM"
   }
}

I used the below technique to do this, but the first value UserDepartmentName is not appear:

jsonconvert(json) {
 
    const obj = JSON.parse('{ "UserDepartmentName": { "OldValue":"Abc123", "NewValue": "Abc123456"  }, "ModifiedDate": { "OldValue":"5/19/2021 12:37:22 PM", "NewValue": "5/24/2021 4:12:21 PM"  } }');
 
    console.log(json);
 
    for (var i in obj) {
      console.log(obj[i]);
    }
 
  }

How to convert the (string) value to (array of JSON) using (TypeScript in Angular 8)?

Note:

  • The string data is dynamic and every time it will be changed
  • The first value in the string is always changing
  • OldValue & NewValue is always there under one of the object

1 Answer 1

2

If you log console.log(obj) you can see that it is being parsed. If I run your code, it actually does log the value of 'UserDepartmentName' - but not the key it self:

{OldValue: "Abc123", NewValue: "Abc123456"}
{OldValue: "5/19/2021 12:37:22 PM", NewValue: "5/24/2021 4:12:21 PM"}

If you want to log the key, you can iterate like so:

for (var i in obj) {
    console.log(i + '= ', obj[i]);
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.