0

When I try to load a json file using following code, it gives some u characters:

import json

with open('strings.json') as json_data:
    d = json.load(json_data)
    print(d)

 [{u'goat': 45}, {u'chicken': 45}]

what is going on ? any ideas ?

Media
  • 47
  • 2
  • 3
    Possible duplicate of [Python: json.loads returns items prefixing with 'u'](https://stackoverflow.com/questions/13940272/python-json-loads-returns-items-prefixing-with-u) – Adrian Pop Dec 18 '18 at 09:47
  • 1
    `u` stands for unicode characters – Sumedh Junghare Dec 18 '18 at 09:47
  • The u is not a character, it is a prefix. – MisterMiyagi Dec 18 '18 at 09:56
  • The `u` isn't doing any harm. It isn't a part of your data, it is just specifying that your keys are Unicode. When you print a Python data structure (like a list of dicts, as here) you often get a representation that you could use in Python code to recreate that structure. If you want it formatted in a particular way then you need to say how you want it formatted, instead of taking the interpreter's default representation. Simple example: `for k,v in d.items(): print(k,',',v)`. – BoarGules Dec 18 '18 at 10:57

3 Answers3

2

u' is the prefix for Unicode characters

Franco Piccolo
  • 6,845
  • 8
  • 34
  • 52
1

The u that you see stands for unicode, which is a really common codification system that allows you to manage almost all characters present in all living languages.
It is a good idea to keep your string codified in unicode, but if you want to print out a string without the u at the beginning, you can use:

print(mystring.encode("utf-8"))

Here you can follow a SO discussion on the u prefix, where someone also cite this amazing article on codification.

Gsk
  • 2,929
  • 5
  • 22
  • 29
-1

You can not use '' for JSON format. You have to use "" for JSON format. And You had used u'something' Unicode format. No need to use Unicode in this section. Sometime need to encode b'' for Binary.

So your code look like

import json

with open('strings.json', encoding("utf-8")) as json_data:
    d = json.load(json_data)
    print(d)

   #[{"goat": 45},{"chicken": 45}]
Md Jewele Islam
  • 939
  • 8
  • 18