doushi1510 2015-04-01 17:48
浏览 48
已采纳

PHP-> Python JSON问题

What am I doing wrong? Python3:

>>> import json
>>> s = "\"{'key': 'value'}\""
>>> obj = json.loads(s)
>>> obj['key']
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: string indices must be integers

Given JSON string is produced by json_encode() from php

Real string: {sessionid:5,file:\/home\/lol\/folder\/folder\/file.ttt}.

UPDATE: Problem is because i transfer json string as command line to shell_exec in php, and read it using sys.argv[1]... So quotes are removed by shell.

PHP Code (which runs python script with shell_exec)

$arg = json_encode(['sessionid' => $session->getId(), 'file' => $filename]);
shell_exec('python3 script.py ' . $arg);

Python code:

import json, sys
s = json.loads(sys.argv[1]) #fails already
  • 写回答

3条回答 默认 最新

  • douhezhan5348 2015-04-01 19:11
    关注

    Kasra answer is correct, ast does the trick, but, additionally i had to 'fix' my string with php - to prevent 'damaging' (by shell?):

    php code:

    $cmd = json_encode(['sessionid' => $session->getId(), 'file' => $filename]);
    $cmd = str_replace('"', '\'', $cmd);
    $cmd = str_replace('\\/', '/', $cmd);
    $cmd = 'python3 program.py "' . $cmd . '"';
    exec($cmd);
    

    python code:

    import json, sys, ast  
    task = json.loads("\"" + sys.argv[1] + "\"")
    task = ast.literal_eval(task)
    
    sessionid = task['sessionid'] # DONE!:)
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记