0

Im trying to turn an Object created in js into JSON and then passed to my back-end in Django.

First I make a list of lists:

function get_account_info(){ var account_list = []; $('.card').each(function(e){ var account = []; account.push($(this).find('.name').val()); account.push($(this).find('.username').val()); account.push($(this).find('.password').val()); if(account[0] != null){ account_list.push(account); } }) return account_list; } 

Then I try to post it:

var account_info_json = JSON.parse(get_account_info()); $.ajax({ type:'POST', url:'/create_new_group/create_group/', data:{ csrfmiddlewaretoken:$('input[name=csrfmiddlewaretoken]').val(), account_info: account_info_json, } , success:function(data){ if(data.status == 1){ //success! console.log('Success!') } else if(data.status == 2){ //failed console.log('Failed!') } } 

And this is what I get when I print(json.dumps(request.POST)) in my views.py

{"csrfmiddlewaretoken": "token_data_is_here", "account_info": "[[\"1111111\",\"1111111\",\"1111111\"],[\"222222\",\"222222\",\"222222\"]]"} 

I can only acces this data like a stirng, not JSON. How can I make it so I access it like JSON?

2 Answers 2

1

all the data will be converted to string before it is sent, so when it comes to django you need to first convert string to json.

to convert from string to json:

import json str = json.loads(json_data) 

to obtain json from string:

import json json_data = json.loads(str) 

in your case you need to convert string to json before accessing it as a dictionary in python

hope it helps!!

Sign up to request clarification or add additional context in comments.

Comments

1

You have deserialize json string first:

import json account_info = json.loads(request.POST['account_info']) 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.