Eric Johnson
Eric Johnson

Reputation: 13

JSON.parse() returning string from PythonShell string

I'm using PythonShell from Node to run a Python script that returns a Python dict like so (in Python):

{ "playedStatus": game['playedStatus'].encode('ascii'),
"awayTeamAbb": game['awayTeamAbb'].encode('ascii'),
"homeTeamAbb": game['homeTeamAbb'].encode('ascii'),
"sport": 'NFL'}

When the Python dict is passed back to Node it's in string format like so:

{'home': 'CHI', 'sport': 'NFL', 'playedStatus': 'UNPLAYED', 'away': 'SEA'}

I've tried to run this string through JSON.parse in a couple different ways to use it as a Javascript object. However, I continue to get a string back instead of an object.

let parsed_JSON = JSON.parse(JSON.stringify(python_string_object));
console.log(typeof parsed_JSON); //returns 'string'

What am I doing wrong? How can I convert this into an object?

Upvotes: 1

Views: 1456

Answers (3)

Steve Bohmbach
Steve Bohmbach

Reputation: 337

python_string_object={'home': 'CHI', 'sport': 'NFL', 'playedStatus': 'UNPLAYED', 'away': 'SEA'}

let parsed_JSON = JSON.parse(JSON.stringify(python_string_object));

console.log(typeof parsed_JSON);//object

python_string_object="{'home': 'CHI', 'sport': 'NFL', 'playedStatus': 'UNPLAYED', 'away': 'SEA'}"

let parsed_JSON2 = JSON.parse(JSON.stringify(python_string_object));

console.log(typeof parsed_JSON2);//string

If you do a typeOf on your python_string_object right when you get it, it will be of type string. there is no need to JSON.stringify()2 it

Upvotes: 0

rafaismyname
rafaismyname

Reputation: 188

First get your python script to return the JSON dump not the dict:

import json

my_dict = {'home': 'CHI', 'sport': 'NFL', 'playedStatus': 'UNPLAYED', 'away': 'SEA'}
json_dict = json.dumps(my_dict)
print(json_dict)

then in your node side get python-shell to parse using json mode and you're done:

const PythonShell = require('python-shell');

const pyshell = new PythonShell('script.py', { mode: 'json' });
pyshell.on('message', function (response) {
  console.log(response); // response is already an object!
});

Upvotes: 1

mindfolded
mindfolded

Reputation: 226

I think you need to take your dictionary and use python's json package to turn it into proper json. First, use json.loads() to turn the dictionary to a string and then you can use json.dumps() and return the result in your python script to make sure the dictionary is output in json form.

I believe this is a duplicate of this question: Converting Dictionary to JSON in python

Upvotes: 0

Related Questions