Sign up ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.

I have been trying to convert a string of dictionary objects as given below

"{'Cmd': None, 'Hostname': None, 'Entrypoint': None, 'Env': None,     'OpenStdin': False, 
'Tty': False, 'Domainname': None, 'Image': u'nginx:latest', 'HostConfig':   
{'Binds': None, 'RestartPolicy': {}, 'NetworkMode': u'bridge', 'Dns': None, 
'Links': [], 'PortBindings': {}, 'DnsSearch': None, 'Privileged': False,
'VolumesFrom': []}, 'ExposedPorts': {}, 'User': None}"

to python dictionary.

But the solutions came up while searching were suggesting to use python ast library for the purpose. as

import ast
ast.literal_eval(string)

And it works fine. But is ast library is built indented to solve problems like this ? Is there any good approach other than this to solve the problem ?

share|improve this question
    
Welcome to Code Review! I'm afraid this question does not match what this site is about. Code Review is about improving existing, working code. The example code that you have posted is not reviewable in this form because it's so short it leaves us guessing at your intentions. Unlike Stack Overflow, Code Review needs to look at concrete code in a real context. Please see Why is hypothetical example code off-topic for CR? In particular though, we'd need to know where the data comes from to understand what to expect from it. –  SuperBiasedMan yesterday
    
Usually when you try to do something with an eval, there's a better way available. –  Mast yesterday
1  
Hmm... While your code is short, it looks real to me, and I see no reason to close it. To me your code needs no guessing..... –  rolfl yesterday
1  
You tagged the question as json, but your string is not quite valid JSON (None instead of null, etc.) -- if it were, you could simply use json.loads from the Python standard library. –  Marcel Stimberg yesterday
    
And don't cross-post. –  jonrsharpe yesterday

1 Answer 1

up vote 2 down vote accepted

To answer your question, yes ast is ok to be used for this. Per the documentation for literal_eval:

Safely evaluate an expression node or a Unicode or Latin-1 encoded string containing a Python literal or container display. The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.

This can be used for safely evaluating strings containing Python values from untrusted sources without the need to parse the values oneself. It is not capable of evaluating arbitrarily complex expressions, for example involving operators or indexing.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.