Hi
I am trying to send json data over a pipe but cannot get it quite right
Send
mesages = [{"id": "1", "txt": "message 1", "start_date": "2014-02-09", "start_time": "16:20", "duration": "01:00"}]
win32file.WriteFile(handle, str.encode(json.dumps(mesages), encoding="ascii"))
receive
result, data = win32file.ReadFile(p, 65535)
json_data = json.dumps(data.decode('ascii'))
print(json_data['first_name'])
This gives me this error
[error
TypeError: string indices must be integers
[/error]
What is the correct way of doing this?
Shouldn't you be calling loads
, rather than dumps
to decode the JSON string into Python objects?
I still get TypeError: string indices must be integers
import json
mesages = [{"id": "1", "txt": "message 1", "start_date": "2014-02-09", "start_time": "16:20", "duration": "01:00"}]
payload = json.dumps(mesages).encode("ascii")
print(payload)
print(type(payload))
# json can also loads bytes
# but here the encoding is not explicit
data = json.loads(payload)
data2 = json.loads(payload.decode("ascii"))
print(data2)
Output:
b'[{"id": "1", "txt": "message 1", "start_date": "2014-02-09", "start_time": "16:20", "duration": "01:00"}]'
<class 'bytes'>
[{'id': '1', 'txt': 'message 1', 'start_date': '2014-02-09', 'start_time': '16:20', 'duration': '01:00'}]
Hi
Yes this works, but I am reading from a pipe using
result, data = win32file.ReadFile(p, 65535)
This gives me the string
b'"{\\"success\\": \\"true\\", \\"status\\": 200, \\"message\\": \\"Hello\\"}"'
I then decode
d = data.decode('ascii')
Then I do a json load
json_data = json.loads
but when I try to access as a json object I get the error
TypeError: string indices must be integers
How can access the result as a json object
result, data = win32file.ReadFile(p, 65535)
json_data = json.loads(data)
print(json_data['success'])
-
This gives TypeError: string indices must be integers
this will work
import json
spam = b'"{\"success\": \"true\", \"status\": 200, \"message\": \"Hello\"}"'
print(spam.decode())
data = json.loads(spam.decode()[1:-1])
print(data['success'])
but I think there is problem with the data being send/receive - i.e. extra quotes. Probably on the sending site you make too many conversions
Here is my sending code
s = '{"success": "true", "status": 200, "message": "Hello"}'
win32file.WriteFile(handle, str.encode(json.dumps(s)))
yep,
s
is already a JSON string, no need to dump it again
win32file.WriteFile(handle, s.encode())
or
s = {"success": "true", "status": 200, "message": "Hello"}
win32file.WriteFile(handle, json.dumps(s).encode())
then on receiving end
data = json.loads(spam.decode())
Also, didn't work with win32file.WriteFile, not sure if you can skip also encode/decode part