如何正确使用 JSON.stringify 和 PHP 返回的 JS 对象

How to use correctly JSON.stringify with an PHP returned JS object

我有一个 php 脚本,它执行一个 python 脚本,我得到了一个这样的对象:

{'data': [{'article title', 'article description', 'timestamp', 'weburl'}], 'status': 200, 'answers': [1]} 

据我所知,我必须将其从 javascript object 类型转换为 javascript JSON

我试过

myjs = JSON.parse(JSON.stringify(answer))

JSON.stringify(answer)

甚至只是在开头和结尾与 " 连接。但都没有给我带来好结果。那么正确的做法是什么?或者我应该改变 php 方面的东西吗?

php 部分就是这样:


    if ($_GET['times'] == 0) {
        $command = escapeshellcmd('python3 feed.py '. $_GET['subject']);
        $output = json_encode(shell_exec($command));
        
        header('Content-type: application/json');
        echo $output;
    }

这是我的 python 脚本:

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

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

data = []
status = 0
answers = 0
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 = {html.unescape(currentNews["timestamp"]), html.unescape(currentNews["title"]), html.unescape(currentNews["description"]), html.unescape(currentNews["link"])}
                out["data"].append(outnews)
                out["answers"][0] = out["answers"][0] +1
        except:
            error += 1
else:
    out["status"] = 404

print (out)

更改 Python 脚本,使其打印 JSON 而不是 Python 格式。

print(json.dumps(out))

但是,集合不在 JSON 中,因此将 outnews 更改为列表。

outnews = [html.unescape(currentNews["timestamp"]), html.unescape(currentNews["title"]), html.unescape(currentNews["description"]), html.unescape(currentNews["link"])]

然后 PHP 脚本可以简单地 return 给客户端。

    if ($_GET['times'] == 0) {
        $command = escapeshellcmd('python3 feed.py '. $_GET['subject']);
        header('Content-type: application/json');
        passthru($command);
    }

如果 passthru() 不起作用,您可以尝试使用原来的 shell_exec()。您不需要调用 json_encode() 因为它已经编码了。

    if ($_GET['times'] == 0) {
        $command = escapeshellcmd('python3 feed.py '. $_GET['subject']);
        $output = shell_exec($command);
        
        header('Content-type: application/json');
        echo $output;
    }

此外,如果我想取回所有新闻而不是像这样更改 out 和 return:

out = []

error = 0
status = 0
nrOfResults = 0

if requestpost.status_code == 200:
    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 = [html.unescape(currentNews["timestamp"]), html.unescape(currentNews["title"]), html.unescape(currentNews["description"]), html.unescape(currentNews["link"])]
                out.append(outnews)
                nrOfResults = nrOfResults +1
        except:
            error += 1
else:
    status = 404

out.append(status)
out.append(nrOfResults)

#outnews = [html.unescape(currentNews["timestamp"]), html.unescape(currentNews["title"]), html.unescape(currentNews["description"]), html.unescape(currentNews["link"])]
print(json.dumps(out))

js 数组的最后一个元素将是结果数,前一个元素将是源的状态 link。