'convert nested string element into list with one element in python

Hope this is a simple one.

I have the following json:

{
   'listTitle': 'dsadasdsa',
   'chapters': 'testchapter',
   'sublist': [
      {
         'subListCreator': 'jan',
         'item': [
            {
               'itemTitle': 'dasdasd',
               'itemContext': 'None'
            }
         ]
      }
   ]
} 

Of which I can print my testchapter value by doing:

  print(data['chapters'])

Here's the question, I would like to do two things:

  1. Remove the complete chapters element in case there is an empty chapter-string: 'chapters': ''

  2. Convert chapters to a list containing the testchapter-value.

Desired outcome in case of scenario 1:

{
    'listTitle': 'dsadasdsa',
    'sublist': [
       {
          'subListCreator': 'jan',
          'item': [
             {
                'itemTitle': 'dasdasd',
                'itemContext': 'None'
             }
          ]
       }
    ]
 }

Desired outcome in case of scenario 2:

{
    'listTitle': 'dsadasdsa',
    'chapters': [
       'testchapter'
    ],
    'sublist': [
       {
          'subListCreator': 'jan',
          'item': [
             {
                'itemTitle': 'dasdasd',
                'itemContext': 'None'
             }
          ]
       }
    ]
 }

Tried a bunch of things but did not manage so far. Either it remained a string instead of list while looking like a list. Or all the string-characters were converted to individual list elements etc.

Hope you can help me! :)



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source