我有一個php執行python腳本的腳本,我得到了一個像這樣的物件:
{'data': [{'article title', 'article description', 'timestamp', 'weburl'}], 'status': 200, 'answers': [1]}
據我所知,我必須將其javascript JSON從javascript object型別轉換為型別。
我試過
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)
uj5u.com熱心網友回復:
更改 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 腳本可以簡單地將其回傳給客戶端。
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;
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/359494.html
標籤:javascript php json 字符串化
