0

i am trying to load a json file and then trying to parse it later. however, in the output i keep getting the 'u' characters. I tried to open the file with encoding='utf-8' which dint solve the problem. i am using python 2.7. is there a straight forward approach or workaround to ignore and get ride of the 'u' characters in the output.

import json
import io


with io.open('/tmp/install-report.json', encoding='utf-8') as json_data:
    d = json.load(json_data)
    print d

o/p

{u'install': {u'Status': u'In Progress...', u'StartedAt': 1471772544,}}

p.s: i went trough this post Suppress the u'prefix indicating unicode' in python strings but that doesn't have a solution for python 2.7

Community
  • 1
  • 1
cool77
  • 1,086
  • 4
  • 15
  • 31
  • 1
    In short: [**no**](http://stackoverflow.com/questions/761361/suppress-the-uprefix-indicating-unicode-in-python-strings). – Jan Aug 21 '16 at 17:13
  • Why is it an issue? – Padraic Cunningham Aug 21 '16 at 18:11
  • Unicode is nothing to do with the problem. This is the Python (`repr()`) representation of a dictionary full of character strings. If you want a representation in another format such as JSON then use an encoder for that format. – bobince Aug 22 '16 at 00:06
  • @PadraicCunningham that's an issue because this needs to be displayed to an end user who may not be comfortable with these 'characters' – cool77 Aug 22 '16 at 07:37
  • @cool77 But you're already assuming the end user is comfortable with the python `repr` output? First of all, what kind of output do you expect? The time stamp doesn't look end-user friendly either. – roeland Aug 22 '16 at 22:43
  • @roeland i am expecting an output without the 'u' characters in the o/p. something like : {'install': 'Status': 'In Progress...', 'StartedAt': 1471772544,}} well, the time stamp issue i can handle by typecasting the object to string. that's not a prob – cool77 Aug 23 '16 at 10:47

2 Answers2

2

Use json.dumps and decode it to convert it to string

data = json.dumps(d, ensure_ascii=False).decode('utf8')
print data
Naruto
  • 4,221
  • 1
  • 21
  • 32
  • @cool77 Please mark the answer as Correct if it solved your problem – Naruto Aug 21 '16 at 17:22
  • 1
    i tried the solution. it helps. but i need to use the dictionary 'd' from json.load later in the script. by using the json.dumps , i get a string with which i cannot later iterate as in a dictionary/ – cool77 Aug 21 '16 at 17:41
  • So keep both the `d` dictionary and the `data` string and use whichever one you need. – bobince Aug 22 '16 at 00:04
0

u just indicates a Unicode string. If you print the string, it won't be displayed:

d = {u'install': {u'Status': u'In Progress...', u'StartedAt': 1471772544}}

print 'Status:',d[u'install'][u'Status']

Output:

Status: In Progress...
Mark Tolonen
  • 166,664
  • 26
  • 169
  • 251