Raj
Raj

Reputation: 2398

Read a JSON file containing unicode data

Here is the content of my JSON file

cat ./myfile.json

{u'Records': [{u'eventVersion': u'2.0', }]}

How do I read this JSON file?

I tried reading the file with the following code,

def Read_json_file(jsonFile):
   jsonDy = {}
   if os.path.exists(jsonFile):
      with open(jsonFile, 'rt') as fin:
         jsonDy = json.load(fin)
   else:
      print("JSON file not available ->",
                                 jsonFile)
      sys.exit(1)
   print("jsonDy -> ", jsonDy)

But getting the following error,

Traceback (most recent call last):
  File "a.py", line 125, in <module>
    Main()
  File "a.py", line 18, in Main
    content = Read_json_file(eventFile)
  File "a.py", line 44, in Read_json_file
    jsonDy = json.load(fin)
  File "/usr/lib64/python2.7/json/__init__.py", line 290, in load
    **kw)
  File "/usr/lib64/python2.7/json/__init__.py", line 338, in loads
    return _default_decoder.decode(s)
  File "/usr/lib64/python2.7/json/decoder.py", line 365, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "/usr/lib64/python2.7/json/decoder.py", line 381, in raw_decode
    obj, end = self.scan_once(s, idx)
ValueError: Expecting property name: line 1 column 2 (char 1)

What I understand is here u' represents the unicode notation, but not sure how to read this file

PS : I am using Python 2.7

Upvotes: 0

Views: 1216

Answers (2)

Lex Scarisbrick
Lex Scarisbrick

Reputation: 1570

That's not a valid JSON structure. It's a string representation of Python data structure. The appropriate JSON structure would be:

{"Records": [{"eventVersion": "2.0"}]}

It looks like something is writing the JSON with the output of json.loads instead of json.dumps.

Upvotes: 3

Marlon Abeykoon
Marlon Abeykoon

Reputation: 12505

Try this,

import simplejson as json
w = json.dumps({u'Records': [{u'eventVersion': u'2.0', }]})
print json.loads(w)

or use:

import json
w = json.dumps({u'Records': [{u'eventVersion': u'2.0', }]})
print json.loads(w)

I have dumped to json to recreate the issue. You can just use json.loads

Upvotes: 1

Related Questions