You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何正确使用JSON.stringify处理PHP调用Python返回的JS对象数据

问题根源

你遇到的解析失败问题完全是后端输出格式错误导致的,前端的转义操作没有任何作用,核心问题有三个:

  • Python脚本中你定义的outnews是Python集合(set)类型,用了无键的花括号语法,没有字段名,前端就算拿到数据也没法对应文章标题、链接等字段
  • Python脚本直接打印Python字典对象,输出的是符合Python语法的单引号格式字符串,不是符合规范的标准JSON(JSON要求双引号包裹键和字符串值)
  • PHP侧拿到Python输出的非JSON字符串后又做了一次json_encode,相当于给原始内容又套了一层转义,返回给前端的是双重编码后的无效内容
修复步骤

1. 修复Python脚本

修改两处核心逻辑:把集合改成带键的字典、输出标准JSON字符串:

#!/usr/bin/python
import requests
import json 
import html
import sys

requestpost = requests.post('NewsSource')
response_data = requestpost.json()

out = {"data":[], "status":[], "answers":[0]}
searchterm = sys.argv[1]
error = 0

if requestpost.status_code == 200:
    out["status"] = 200
    for news in response_data["news"]:
        try:
            currentNews = json.loads(news)
            if ((html.unescape(currentNews["title"]) != "Array" and html.unescape(currentNews["title"]).lower().find(searchterm.lower()) != -1) or (html.unescape(currentNews["description"]).lower().find(searchterm.lower()) != -1)):         
                # 原代码是集合,改为带键的字典,方便前端取字段
                outnews = {
                    "title": html.unescape(currentNews["title"]),
                    "description": html.unescape(currentNews["description"]),
                    "timestamp": html.unescape(currentNews["timestamp"]),
                    "weburl": html.unescape(currentNews["link"])
                }
                out["data"].append(outnews)
                out["answers"][0] = out["answers"][0] +1
        except:
            error += 1
else:
    out["status"] = 404

# 原代码直接print(out),改为输出标准JSON,ensure_ascii=False避免中文被转义
print(json.dumps(out, ensure_ascii=False))

2. 修复PHP侧代码

Python现在输出的已经是标准JSON字符串,不需要再次编码,同时优化参数处理逻辑避免命令注入风险:

if ($_GET['times'] == 0) {
    // 用escapeshellarg处理参数,避免命令注入
    $subject = escapeshellarg($_GET['subject']);
    $command = 'python3 feed.py '. $subject;
    $output = shell_exec($command);
    
    header('Content-type: application/json');
    // 直接输出原始JSON,不要json_encode
    echo $output;
}

3. 前端接收逻辑

现在接口返回的已经是标准JSON,主流请求库(axios、fetch)会自动解析为JS对象,如果是原生请求拿到原始响应文本,直接解析即可:

// answer为接口返回的原始响应文本
const myjs = JSON.parse(answer);
// 直接读取字段即可
console.log(myjs.status); // 200
console.log(myjs.data[0].title); // 第一条新闻标题

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 14:45:03