Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get rid of the "u" from a decoded JSON object?

Tags:

python

I have a dictionary of dictionaries in Python:

d = {"a11y_firesafety.html":{"lang:hi": {"div1": "http://a11y.in/a11y/idea/a11y_firesafety.html:hi"}, "lang:kn": {"div1": "http://a11y.in/a11ypi/idea/a11y_firesafety.html:kn}}}

I have this in a JSON file and I encoded it using json.dumps(). Now when I decode it using json.loads() in Python I get a result like this:

temp = {u'a11y_firesafety.html': {u'lang:hi': {u'div1': u'http://a11y.in/a11ypi/idea/a11y_firesafety.html:hi'}, u'lang:kn': {u'div1': u'http://a11y.in/a11ypi/idea/a11y_firesafety.html:kn'}}}

My problem is with the "u" which signifies the Unicode encoding in front of every item in my temp (dictionary of dictionaries). How to get rid of that "u"?

like image 554
station Avatar asked Mar 15 '11 14:03

station


People also ask

What does U mean in JSON?

The u- prefix just means that you have a Unicode string. When you really use the string, it won't appear in your data. Don't be thrown by the printed output.

How do I fix JSON decode error?

JSONDecodeError: Extra data" occurs when we try to parse multiple objects without wrapping them in an array. To solve the error, wrap the JSON objects in an array or declare a new property that points to an array value that contains the objects.

How do I decode a JSON file?

You just have to use json_decode() function to convert JSON objects to the appropriate PHP data type. Example: By default the json_decode() function returns an object. You can optionally specify a second parameter that accepts a boolean value. When it is set as “true”, JSON objects are decoded into associative arrays.

How do I remove something from a JSON Python?

To delete a JSON object from a list: Parse the JSON object into a Python list of dictionaries. Use the enumerate() function to iterate over the iterate over the list. Check if each dictionary is the one you want to remove and use the pop() method to remove the matching dict.


1 Answers

Why do you care about the 'u' characters? They're just a visual indicator; unless you're actually using the result of str(temp) in your code, they have no effect on your code. For example:

>>> test = u"abcd"
>>> test == "abcd"
True

If they do matter for some reason, and you don't care about consequences like not being able to use this code in an international setting, then you could pass in a custom object_hook (see the json docs here) to produce dictionaries with string contents rather than unicode.

like image 180
DNS Avatar answered Sep 19 '22 20:09

DNS