2

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 Answers 3

2

Look at this JSON:

"\"{'key': 'value'}\""

You have a string containing an escaped quote, followed by a dictionary-like object, then an escaped quote. When you try to decode this you wind up with the following:

"{'key': 'value'}"

That's a string, not a dictionary.

Sign up to request clarification or add additional context in comments.

9 Comments

Without this, json.loads raises ValueError: Expecting property name enclosed in double quotes: line 1 column 2 (char 1)
Because the inner string is not JSON. JSON always has double quotes around keys and values.
Yep! And such JSON string is produced by json_encode() from php
I would look at your object before it's been serialized in PHP then. You need those quotes to be double, or it isn't valid syntax.
PHP: json_encode(['sessionid' => $session->getId(), 'file' => $filename]) -- python script receives this as a command line argument with shell_exec()
|
1

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

Comments

0

As your string surrounded by 2 quote that you escaped one of them so after reading the string with json the result will be string,So after that you can use ast.literal_eval to convert your string to dictionary :

>>> obj = json.loads(s)
>>> obj
"{'key': 'value'}"
>>> import ast
>>> new=ast.literal_eval(obj)
>>> new['key']
'value'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.