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 有赏,i卡绘世画不出
  • ¥15 如何用stata画出文献中常见的安慰剂检验图
  • ¥15 c语言链表结构体数据插入
  • ¥40 使用MATLAB解答线性代数问题
  • ¥15 COCOS的问题COCOS的问题
  • ¥15 FPGA-SRIO初始化失败
  • ¥15 MapReduce实现倒排索引失败
  • ¥15 ZABBIX6.0L连接数据库报错,如何解决?(操作系统-centos)
  • ¥15 找一位技术过硬的游戏pj程序员
  • ¥15 matlab生成电测深三层曲线模型代码