MHS
MHS

Reputation: 2350

python -- Converting a string into python list

I have a string that contains my data like this:

result = "[
           {'service': {'option1': 'abc', 'others': 'blah blah'}},
           {'service': {'option2': 'None', 'others': 'None'}}
          ]\n
          [
           {'rules': {'permissions': 'allow', 'opp': 'evening', 'order': '10', 'self': 'me'}},
            {'rules': {'permissions': 'not allowed', 'opp': 'None\\n', 'order': 'None', 'self': 'None'}}
          ]"

I want to convert it into a proper list like:

result = [[
          {'service': {'option1': 'abc', 'others': 'blah blah'}},
          {'service': {'option2': 'None', 'others': 'None'}}
         ],
         [
          {'rules': {'permissions': 'allow', 'opp': 'evening', 'order': '10', 'self': 'me'}},
          {'rules': {'permissions': 'not allowed', 'opp': 'None\\n', 'order': 'None', 'self': 'None'}}
         ]]

Kindly help me out! I have tried .split(), .join() but unable to get the exact format like above.

Upvotes: 2

Views: 55

Answers (1)

behzad.nouri
behzad.nouri

Reputation: 77951

you can use ast, ( Abstract Syntax Trees ) with a minor modification of the string,

import ast
ast.literal_eval( '[{}]'.format( result.replace( ']\n', '],' ) ) )

Upvotes: 4

Related Questions