0

I'm using Python 2.7 to convert saved tuples to list/dictionaries.

Currently my code looks like this:

mystring = "\x80\x02]q\x01(J\x03\x00\x01\x00J\x15\xf93PK\x01K\x01G@\x834\x00\x00\x00\x00\x00K\x01K\x00e}q\x02(M\x03\xbb]q\x03(U\x0bmteststringq\x04Ml0U\x05_L-A_q\x05K\x00K\x02eJ\x06M\xd1\x1d]q\x06(U\x08otherstrq"
mystruct = str(len(mystring)) + 'B'
mydict = struct.unpack(mystruct, mystring)

In reality the string is longer, I shortened it. This works for the integer values, but it contains also names like "mteststring" or "otherstr" - how do I get them out of the string along with their values?

5
  • 1
    What you are doing is unpacking it as a bunch of bytes, you need to define the structure. Commented Aug 22, 2012 at 17:06
  • In order to interpret mystring in a meaningful way, there would have to be a seperator between the elements of the tuple. Otherwise how can you distinguish anything? If you are looking for a way to save and retrieve structured information, have a look at e.g. JSON (json.org), or shelve (docs.python.org/library/shelve.html) if you don't mind that the files are not human readable. Commented Aug 22, 2012 at 17:15
  • can you post your original c struct? or original structure? Commented Aug 22, 2012 at 17:17
  • I am not sure what you are asking is possible. Commented Aug 22, 2012 at 17:18
  • That is not my data I'm reading, so I cannot define the struct. I'm just trying to analyze it and convert to JSON. Commented Aug 23, 2012 at 8:50

1 Answer 1

1

As xiaomao commented, you'll need to define the full structure in your mystruct string so something like:

mystruct = "47B12s29B9s"
struct.unpack(mystruct, mystring)

gets you a little closer, in that it's extracting the two strings. Of course if you're writing both ends of this transaction, there are many other encoding methods that could be used, including some such as JSON or YAML which will make the data much more readable/portable.

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

1 Comment

Thats not my data. I'm reading it out from files and converting it to JSON. Reading just integer is no problem at all, just these mixed values are making me headaches.

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.