What is the shortest method to convert a JavaScript object to a JSON object? The beneath is my JavaScript object.
{
"body": [
{
"id": "1",
"action": "alert",
"activityGroupNames": "test2"
},
{
"id": "2",
"action": "alert",
"activityGroupNames": "test3"
},
{
"id": "3",
"action": "alert",
"activityGroupNames": "test2"
}
]
}
I making use of an inline code script in Microsoft automate that performs the following in JavaScript:
var threat = workflowContext.actions.Compose.outputs;
var value = Object.values(threat);
return value;
I am supposed to HTTP POST a JSON object in an API request, however, I am submitting a JavaScript object type and am unsure as to how I can change this. Any help would be greatly appreciated! Please let me know if you require any further context.
Edit: The HTTP POST request is failing due to "Object reference not set to an instance of an object"
CodePudding user response:
Javascript provides with built-in method JSON.stringify() It will help you to convert JavaScript object into JSON and pass through HTTP Request
console.log(JSON.stringify({ x: 5, y: 6 }));
// expected output: "{"x":5,"y":6}"
CodePudding user response:
A common use of JSON is to exchange data to/from a web server. When receiving data from a web server, the data is always a string. Parse the data with JSON.parse(), and the data becomes a JavaScript object.
const json = '{ "fruit": "pineapple", "fingers": 10 }';
const obj = JSON.parse(json);
console.log(obj.fruit, obj.fingers);