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?

7
  • 2
    Possible duplicate of Parse JSON in Python Commented Nov 20, 2018 at 21:43
  • I've tried using json.loads but it doesn't work. I think this is because this is an array and not formatted json Commented Nov 20, 2018 at 21:46
  • 2
    Works just fine for me. Are you certain that your data is in the format posted above? Commented Nov 20, 2018 at 21:50
  • I'll double check to confirm Commented Nov 20, 2018 at 22:06
  • I think the problem is probably with your input, [", "name": "server.posts.serializers", "levelname": "INFO", "request_id": "none"} doesn't seem right to me... Commented Nov 20, 2018 at 22:08

1 Answer 1

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']
Sign up to request clarification or add additional context in comments.

2 Comments

Isn't he doing the json.loads() solution?
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"]

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.