-1

I have a json which looks like the below. When i validate json, i get an error "Invalid Json" since i have just a single quote and also, there is u which i can't tell why it is there.

{u'domain': u'127.0.0.1', u'user_id': u'example.com', u'sender': u'shop_1'}

The Json above is invalid. How can i make the json appear with double quotes and also remove the u from the response to get a valid json.

PS: Beginner with Python

  • how do you create that json? – Stefano Borini Sep 24 '19 at 09:42
  • If what you've showed, is your json file, just replace `u'` and `'` with `"`s. You can do that in your text editor of choice, or even in python, before loading, run `text.replace("u'", '"').replace("'", '"')` – tituszban Sep 24 '19 at 09:43
  • This is a Python object (saved as string ?!), which is not valid JSON. – Maurice Meyer Sep 24 '19 at 09:44
  • 2
    json.dumps() returns the JSON string representation of the python dict. https://docs.python.org/2/library/json.html#json.dumps – Yaman Jain Sep 24 '19 at 09:46
  • duplicate of https://stackoverflow.com/questions/26745519/converting-dictionary-to-json – Yaman Jain Sep 24 '19 at 09:47
  • 1
    Btw, You are still using Python2; you should switch to Python3 which is around for a decade or more now. The `u` in front of the string literal marks it as a unicode string (in Python3 that is the normal string, but in Python2 is wasn't). – Alfe Sep 24 '19 at 09:47
  • that is not a json. that looks like a python dictionary literal. are you simply dumping the string representation of a dictionary and imagining it will be JSON? – juanpa.arrivillaga Sep 24 '19 at 09:48

1 Answers1

4

You can use json.dumps() for that:

>>> import json
>>> my_json = {u'domain': u'127.0.0.1', u'user_id': u'example.com', u'sender': u'shop_1'}
>>> print(json.dumps(my_json))
{"domain": "127.0.0.1", "user_id": "example.com", "sender": "shop_1"}

The 'u that you see at the start of each string is an indication that this is a unicode string:

Lix
  • 47,311
  • 12
  • 103
  • 131
Silveris
  • 1,048
  • 13
  • 31