0

I've sent some form-data from my React client to my Django + DRF api.

inside of the form-data I have an attribute date_strings which is an array of date-time strings. i.e. ["date1", "date2", "date3"]

in order to send it to my Django api I converted the array of strings into a string using JSON.stringify

const myForm = new FormData();
myForm.set("date_strings", JSON.stringify(dateStrings));

in the create method of my serializer, I'd like to convert this data into a list.

 def create(self, validated_data):
    stringified_array = validated_data.pop('date_strings')
    // stringified_array: '["date1", "date2", "date3"]'

how can I convert an array of strings inside of a string into a python list?

Brooklin Myers
  • 313
  • 2
  • 17

1 Answers1

1

You can easily turn strings into lists using .split. However, you have to remove the outermost characters [" and "] because otherwise these will also be added to your list of strings.

stringified = '["date1", "date2", "date3"]'
unstringified = stringified[2:-2].split('", "')

returns

['date1', 'date2', 'date3']

A much better solution as mentioned by @mhodges

import json
stringified = '["date1", "date2", "date3"]'
unstringified = json.loads(stringified)

Which also outputs:

['date1', 'date2', 'date3']
Nathan
  • 3,558
  • 1
  • 18
  • 38
  • Isn't he doing the `json.loads()` solution? – Barmar Nov 20 '18 at 22:12
  • This is the correct answer! I made a mistake, json.loads() works correctly. I tried using json.loads before, but I had a log below it so kept getting the message `["TypeError: must be str, not type\n"]` – Brooklin Myers Nov 20 '18 at 22:17