Question

I'm trying to get a user input and from that create a json object and sent it through a tcp socket.. but I am sending a wrong json object beacuse the server can't deserialize it (but it works if I send the json directly from the code. Here is my code:

import socket
import json

TCP_IP = '132.72.213.108'
TCP_PORT = 6666
BUFFER_SIZE = 1024

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((TCP_IP, TCP_PORT))
typeText = raw_input("Enter the type: ")
argumentsText = raw_input("Enter arguments: ")
while (typeText != "end"):
  argumentsText = argumentsText.replace(",","\",\"");
  argumentsText = "\"" + argumentsText + "\""
  data = '{"type":'+typeText+',"parameters":['+argumentsText+']}'
  print(str({'type':typeText,'parameters':[argumentsText]}))
  s.send(json.dumps(data))
  result = json.loads(s.recv(1024))
  print("received: " + str(result)+"\n")
  typeText = raw_input("Enter the type: ")
  argumentsText = raw_input("Enter arguments: ")
s.close()
Was it helpful?

Solution

You are trying to convert str value (looking like a JSON) into JSON string.

json.dumps is to convert Python variables like a dictionary, into JSON string.

dct = {}
dct["a"] = "Ahahaha"
dct["b"] = 3.14

import json

print json.dumps(dct)

So for your case:

  1. first create valid data structure (like dictionary) with the data you are going to send out
  2. then use json.dumps to convert it to real JSON string and send it out.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top