2

I am having a list of jsons in a text file as

[{"key1": "value1", "key2": "value2"},{},{}]

Now I am trying to read the file and converting it into list of dicts so that I can iterate and use those key-value pairs using code -

with open('./file.txt') as f:
   listOfDict= json.load(f)

I am getting error -

ValueError: Invalid \escape: line 1 column 2005707 (char 2005706)

I think that might be because some of the values are like - For eg. {"key1":"ENERGIZER\xc2"}

I forgot to use text.encode("utf-8") while writing to this file. Instead I used str(text) while writing to the file.

Is this is the reason for this error and how can I resolve this issue.

2
  • is this python 2 or 3?
    – Daniel
    Aug 13, 2016 at 10:00
  • @DanielG Python 2.7
    – sagar
    Aug 13, 2016 at 10:07

1 Answer 1

1

Ok, you'll have to do a little string manipulation to unescape and decode.

It depends on whether your data contains escaped Unicodes or escaped 8bit characterset, like latin1 or cp1252. You'll have to experiment to see what works for your data.

If it's escaped Unicode you can simply do:

import io
with io.open('./file.txt', 'r', encoding='unicode_escape') as f:
    listOfDict= json.load(f)

If escaped 8bit 'latin1', you'll need to do:

with open('./file.txt', 'r') as f:
    # read, convert escape to byte, convert bytes as 'latin1'
    decoded_json = f.read().decode('string_escape').decode('latin1')
    listOfDict = json.loads(decoded_json) # Note the "s".
2
  • What does str.decode('string_escape') function do? I am having urls in the text file, like "https://" does that gonna affect those too, please also tell, what I had missed out while saving the text file, since I am getting these errors.
    – sagar
    Aug 13, 2016 at 10:57
  • 1
    string_escape works on just backslashes. text.encode("utf-8") wouldn't have fixed your data - something else is at play - you probably saved the repr() of the string by mistake Aug 13, 2016 at 11:35

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.