0

I have this String (representing a JSON value):

BABEL_JSON = "{
    'BD': u'Bangladesh', 
    'WF': u'Wallis y Futuna', 
    'BF': u'Burkina Faso'
}"

and I need to transform into a List object like this:

BABEL_LIST = [
    ("BD", u"Bangladesh"),
    ("WF", u"Wallis y Futuna"),
    ("BF", u"Burkina Faso")
]

What is the best way? to begin I tried with:

import json
BABEL_LIST = json.loads(str(BABEL_JSON))

but I have this error:

TypeError: 'NoneType' object is not callable
1
  • 10
    That isn't valid JSON. If BABEL_JSON was a dictionary, you could just use BABEL_JSON.items() to get BABEL_LIST. Commented Oct 8, 2012 at 5:52

5 Answers 5

3

You need to use literal eval as your content is not valid JSON, it is a python dictionary as a string.

literal eval safely evaluates valid python objects.

import ast


BABEL_JSON = """{                                                               
    'BD': u'Bangladesh',                                                        
    'WF': u'Wallis y Futuna',                                                   
    'BF': u'Burkina Faso'                                                       
}"""

myDict = ast.literal_eval(BABEL_JSON)
print(myDict.items())
Sign up to request clarification or add additional context in comments.

Comments

1

You don't have a valid json string. In json, strings are written with ". The u in front of a string is not allowed too. You have to transform your initial json-like string to a valid one:

import json
BABEL_JSON ="""{
    'BD': u'Bangladesh', 
    'WF': u'Wallis y Futuna', 
    'BF': u'Burkina Faso'
}"""
s = BABEL_JSON.replace(": u", ": ").replace("'", '"')
print json.loads(s).items()

See http://ideone.com/OxPml

Comments

1
import json
a = json.loads(l)
zip(a.keys(),a.values())

another way

import ast
a = ast.literal_eval(l)
zip(a.keys(),a.values())

1 Comment

more efficient to use a.items()
0

Or use regex like this:

import re

BABEL_JSON = """{
    'BD': u'Bangladesh', 
    'WF': u'Wallis y Futuna', 
    'BF': u'Burkina Faso'
}"""

print re.findall(r"'([^']+)': u'([^']+)'", BABEL_JSON)

Output:

[('BD', 'Bangladesh'), ('WF', 'Wallis y Futuna'), ('BF', 'Burkina Faso')]

Comments

0

It is the best and fastest way to do it I found

BABEL_JSON = "{
    'BD': u'Bangladesh', 
    'WF': u'Wallis y Futuna', 
    'BF': u'Burkina Faso'
}"

BABEL_LIST = [(key, countries[key]) for key in BABEL_JSON]

And if you want to sort them by the name.

BABEL_LIST.sort(key=lambda tup: tup[1])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.