如何解析JavaScript中JSON字符串的normal、soft、adult字段值
Hey there! Let's sort this out quickly—you're closer than you think to getting those values.
First, a quick key point: when you ran console.log(JSON.stringify(body)) and got that escaped JSON string, that means the original body variable is already a JavaScript object! You don't need to convert it to a string first; you can directly access its properties.
Option 1: Use the Original body Object (Recommended)
Since body is already parsed and ready to use, just drill down into its nested properties like this:
// Grab each value directly from the body object const normalScore = body.result.normal; const softScore = body.result.soft; const adultScore = body.result.adult; // Test the extracted values console.log(normalScore); // Output: 0.002 console.log(softScore); // Output: 0.776 console.log(adultScore); // Output: 0.222
Option 2: If You Only Have the JSON String (e.g., Copied from Logs)
If you're working with the escaped string from your log output instead of the original body object, use JSON.parse() to convert it back into a usable JavaScript object:
// The JSON string from your logs (note: backslashes are only for escaping in the log display) const jsonString = '{"result":{"normal":0.002,"soft":0.776,"adult":0.222}}'; // Parse the string into an object const parsedData = JSON.parse(jsonString); // Extract the values you need const normalScore = parsedData.result.normal; const softScore = parsedData.result.soft; const adultScore = parsedData.result.adult; console.log(normalScore); // 0.002
Quick Recap
JSON.stringify()takes a JavaScript object and turns it into a string (which is what you used to log your data).JSON.parse()does the reverse: converts a JSON string into a usable object.
Since you already had the body object to begin with, Option 1 is the simplest and most efficient way to get your values.
内容的提问来源于stack exchange,提问作者seongho Joo

