You need to enable JavaScript to run this app. 如何从moderatecontent API返回的响应中提取predictions下的adult评分值
优惠活动
大模型
产品
解决方案
定价
更多

如何从moderatecontent API返回的响应中提取predictions下的adult评分值

核心报错原因
  • 你直接访问xhttp.responseText.predictions取不到值,本质是responseText返回的是纯文本格式的JSON字符串,不是能直接用点语法访问属性的JS对象。字符串本身没有predictions这个属性,所以访问结果要么报类型错误,要么输出undefined。
  • 之前用this.adult取值失败,是因为这个回调函数里的this指向当前的XMLHttpRequest实例,根本不包含接口返回的业务数据字段,自然拿不到目标值。
可直接运行的修正方案
  1. 拿到接口返回文本后,先通过JSON.parse()将JSON格式字符串解析为标准JS对象
  2. 按照返回结构的嵌套层级,逐层访问属性即可拿到对应的adult预测评分
    修正后的完整代码如下:
var ajax_url = "https://api.moderatecontent.com/moderate/";
var image_url = "sample_face_2.jpg"; 
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (xhttp.readyState == 4 && xhttp.status == 200) {
        // 解析字符串格式的返回值为可操作的JS对象
        try {
            const responseData = JSON.parse(xhttp.responseText);
            // 按嵌套路径提取adult评分值
            const adultPredictScore = responseData.predictions.adult;
            console.log("成人内容预测评分:", adultPredictScore);
        } catch (err) {
            console.error("接口返回格式解析失败:", err);
        }
    }
};
xhttp.open("GET", ajax_url + "?key=1234567890&url=" + image_url, true);
xhttp.send();
补充说明
  • 其他字段的提取逻辑和adult完全一致:如果要拿顶层的rating_label值,直接访问responseData.rating_label即可,不需要额外嵌套层级。
  • 加try/catch包裹解析逻辑,是为了避免接口返回非JSON格式的异常内容(比如网络错误返回的提示文本)导致整个页面脚本崩溃。

内容的提问来源于stack exchange,提问作者Cohen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.23 02:54:03