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

Time:11-19

I have a php script which executes a python script and I got back an object like this:

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

As I know I have to transform this into a javascript JSON from a javascript object type.

And I tried like

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

and

JSON.stringify(answer)

or even just concatenate with "on the beginning and at the end. But neither got me a good result. So what is the correct way? or should I change something on php side?

The php part is simply this:


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

This is in my python script:

#!/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)

CodePudding user response:

Change the Python script so it prints JSON instead of Python format.

print(json.dumps(out))

However, sets aren't in JSON, so change outnews to a list.

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

Then the PHP script can simply return that to the client.

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

If passthru() isn't working, you can try with your original shell_exec(). You don't need to call json_encode() because it's already encoded.

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

CodePudding user response:

Also If I want to get back all news than change out and return it back like this:

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))

than the last element of js array will be a the number of results and the before one will be the status of the source link.

  • Related