-2

I get this string from stdin.

{u'trades': [Custom(time=1418854520, sn=47998, timestamp=1418854517, price=322, amount=0.269664, tid=48106793, type=u'ask', start=1418847319, end=1418847320), Custom(time=1418854520, sn=47997, timestamp=1418854517, price=322, amount=0.1, tid=48106794, type=u'ask', start=1418847319, end=1418847320), Custom(time=1418854520, sn=47996, timestamp=1418854517, price=321.596, amount=0.011, tid=48106795, type=u'ask', start=1418847319, end=1418847320)]}

My program fails when i try to access jsonload["trades"]. If i use jsonload[0] I only receive one character: {.

I checked it isn't a problem from get the text from stdin, but I don't know if it is a problem of format received (because i used Incursion library) or if it is a problem in my python code. I have tried many combinations about json.load/s and json.dump/s but without success.

inputdata = sys.stdin.read()

jsondump = json.dumps(inputdata)

jsonload = json.loads(jsondump)

print jsonload
print type(jsonload) # return me "<type 'unicode'>"
print repr(jsonload) # return me same but with u" ..same string.... "
for row in jsonload["trades"]: # error here: TypeError: string indices must be integers
Matthew Franglen
  • 4,441
  • 22
  • 32

1 Answers1

1

You read input data into a string. This is then turned into a JSON encoded string by json.dumps. You then turn it back into a plain string using json.loads. You have not interpreted the original data as JSON at any point.

Try just converting the input data from json:

inputdata = sys.stdin.read()
jsonload = json.loads(inputdata)

However this will not work because you have not got valid JSON data in your snippet. It looks like serialized python code. You can check the input data using http://jsonlint.com

The use of u'trades' shows me that you have a unicode python string. The JSON equivalent would be "trades". To convert the python code you can eval it, but this is a dangerous operation if the data comes from an untrusted source.

Community
  • 1
  • 1
Matthew Franglen
  • 4,441
  • 22
  • 32
  • Yes, print type(jsonload) # return me "" . I read now about eval but it is a trusted environment because i generated the output from another script, but i prefer dont use it. But i cant understand why Incursion library works but not for me , i think so i forgetting something to do in middle. – raúl andrés Dec 18 '14 at 12:26
  • In your original code that really just indicates that your strings are unicode. You have not parsed your string so that doesn't actually tell you anything. – Matthew Franglen Dec 18 '14 at 12:28
  • Then i nead research about how to parse unicode, true? – raúl andrés Dec 18 '14 at 12:45
  • No, unicode is a format of string. I would suggest that you need to generate JSON data instead of stringified python. – Matthew Franglen Dec 18 '14 at 13:16