-3

I have a json response that looks like:

response ={u'connections': [{u'pair': [u'5', u'14'], u'routes': 
      [[u'5', u'6', u'13', u'14'], [u'5', u'7', u'10', u'4', 
      u'14']]}], u'succeeded': True})

I need to convert this unicode string to string.

I want it to look like :

response={'connections': [{'pair': ['5', '14'], 'routes': [['5', '6', 
     '13', '14'], ['5', '7', '10', '4', '14']]}], 'succeeded': True})

How can this be achieved?

wyse12
  • 7
  • 4
  • 4
    Abandon Python-2.7 and switch to Python-3.x. – DYZ Mar 27 '18 at 06:09
  • 1
    why do you want to do that? requests lib supports this thing. Unicode input is supported there – Arpit Solanki Mar 27 '18 at 06:10
  • 1
    This is a bad idea, unless you really have a good reason for it. But if you really want to do this, the only option is to walk the structure and encode all strings as you visit them. Something like [this](https://gist.github.com/abarnert/26c44c41747ec5e380bba848ed982673). – abarnert Mar 27 '18 at 06:23

2 Answers2

3

Unless you have a good reason for doing this, you really shouldn't. Your code should be using unicode internally, and only converting to and from encoded bytes at the edges—and at the edges, you're probably going to be writing out something like json.dump(response), not individual elements of response. (Not to mention that most libraries you're likely to be using this with, like requests or Flask, already do that encoding for you.)

But iIf you really want to convert all the strings in an arbitrary structure consisting of unicode strings, other atoms that don't need to be converted, and lists and dicts as the only collections, you have to walk the structure and encode each string as you visit it. Something like this:

def deep_encode(obj, encoding):
    if isinstance(obj, unicode):
        return obj.encode(encoding)
    elif isinstance(obj, dict):
        return {deep_encode(key, encoding): deep_encode(value, encoding) for key, value in obj.items()}
    elif isinstance(obj, list):
        return [deep_encode(item, encoding) for item in obj]
    else:
        return obj
abarnert
  • 354,177
  • 51
  • 601
  • 671
1

Here is my solution to the given problem :

import json, ast
mynewDix = {}
response ={u'connections': [{u'pair': [u'5', u'14'], u'routes': 
      [[u'5', u'6', u'13', u'14'], [u'5', u'7', u'10', u'4', 
      u'14']]}], u'succeeded': True}

for key in response.keys():

    if type(response[key]) == bool :
            valueToDump = json.dumps(str(response[key]))
    else:
        valueToDump =  json.dumps(response[key])

    mynewDix[ast.literal_eval(json.dumps(key))] = ast.literal_eval(valueToDump)
print mynewDix

output : {'connections': [{'pair': ['5', '14'], 'routes': [['5', '6', '13', '14'], ['5', '7', '10', '4', '14']]}], 'succeeded': 'True'}

I am not sure about succeeded value will True as a string work for you ?

hope this helps .

toheedNiaz
  • 1,435
  • 1
  • 10
  • 14