我是计算机科学的初学者。 我想知道如何在python中控制JSON数据
在nodeJS服务器中,像这样执行python模块
const data = {"uid":"XZsGi9A93NNH4fRYYI5a2Wk4Hfm1","lat":"37.5916983","lng":"127.01206040000001"};
pythonShell.run('/python/test.py',options,(err,results)=>{
if(err){
res.send("Error : ", err);
}else{
console.log(results);
res.send(JSON.stringify(results));
}
})
这是test.py
import sys
print(sys.argv[1])
结果就像这样
{ uid: 'XZsGi9A93NNH4fRYYI5a2Wk4Hfm1',
lat: '37.591696899999995',
lng: '127.0120884' }
正如你看到uid,lat,lng不是“uid”,“lat”,“lng”,所以我不能用这个数据在python中进行dict ...
如何在python中控制json数据??? 或者如何使用json数据传递nodejs和python?
答案 0 :(得分:0)
$customer = \Stripe\Customer::create(array(
'email' => $email,
'source' => $token
));
if(!empty($recurring_duration)){
try {
$plan = \Stripe\Plan::retrieve($planname);
//got plan
} catch (Error\InvalidRequest $exception) {
//create new plan
$plan = \Stripe\Plan::create(array(
"name" => "Basic Plan",
"id" => $planname,
"interval" => "$recurring_duration",
"currency" => strtolower($currency),
"amount" => $amount,
));
}
$charge = \Stripe\Subscription::create(array(
"customer" => $customer->id,
"items" => array(
array(
"plan" => $planname,
),
),
));
}else{
$charge = \Stripe\Charge::create(array(
'customer' => $customer->id,
'amount' => $amount,
'currency' => strtolower($currency),
'description' => '',
)
);
}
$val = BSP_add_form_data($charge);
那是因为你只是打印输入字符串
答案 1 :(得分:0)
在python中“控制”json:
import json
#data is your json in a dict
data = {...}
#To print, store etc CONVERT json into String
json.dumps(data)
#To read json in string, your call JSON.stringify(results) converts json to string
data = json.loads(input) #input = sys.argv[1]
答案 2 :(得分:0)
您正在使用 python-shell 模块的run
方法,该方法更适合启动带参数的脚本,而不是传递JSON数据。
python-shell 提供了send
方法,可以更轻松地与python脚本进行数据交换。
以下是一个使用示例,灵感来自python-shell tests:
server.js
const PythonShell = require('python-shell');
const pyshell = new PythonShell('/python/test.py');
const data = {"uid":"XZsGi9A93NNH4fRYYI5a2Wk4Hfm1","lat":"37.5916983","lng":"127.01206040000001"};
pyshell.send(JSON.stringify(data), { mode: 'json' });
pyshell.on('message', results => {
console.log(results);
res.send(results);
});
pyshell.end(err => {
if (err) res.send("Error : ", err);
});
test.py
import sys, json
for line in sys.stdin:
print json.dumps(json.loads(line))