Home > Software design >  Access value from a string object - Javascript
Access value from a string object - Javascript

Time:03-22

Not sure why I am not able to access the keys from a string object data looks like this I am getting this data from a python variable

const data = '{regression: {success: 7310, total: 14154, failed: 4665, unstable: 2104, aborted: 75}, stable: {success: 2699, total: 4252, failed: 462, unstable: 15, aborted: 1076}, patch: {success: 2824, total: 5494, failed: 2518, unstable: 39, aborted: 113}}'

I need to extract the keys regression, stable, patch and eventually the details of how many test cases were in success, total, failed etc.

Tried to change the string to object using JSON.parse(data) but it gives error as its not an object.

How can I extract the keys and value in this case

CodePudding user response:

There is an easy approach to make this work.

In your Python code, use the json.dumps() method to convert a Python dictionary into valid JSON, like below.

import json

dictonary = {
  "name": "Name",
  "age": 0
};

print(json.dumps(dictionary)) # Returns JSON

Then, in your JavaScript, add the following code.

const data = "{\"name\": \"Name\", \"age\": 0}";
console.log(JSON.parse(data)); // Returns a JavaScript object

The JavaScript code should now return a JavaScript object without any errors.

  • Related