-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?

3
  • 4
    Abandon Python-2.7 and switch to Python-3.x. Commented Mar 27, 2018 at 6:09
  • 1
    why do you want to do that? requests lib supports this thing. Unicode input is supported there Commented Mar 27, 2018 at 6: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. Commented Mar 27, 2018 at 6:23

2 Answers 2

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 
Sign up to request clarification or add additional context in comments.

Comments

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 .

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.