Django Trying to save my Array to the model - javascript

I have the following data coming from the
manager_item = request.POST.getlist(manager_type_item)
in my views:
['{"id":"1","title":"Bedroom"},{"id":"2","title":"Taps"}, {"id":"3","title":"Living Room"}']
Basically each one of these are {"id":"1","title":"Bedroom"} will need t be added into the model:
index = 0
for index, item in enumerate(json.loads(manager_item)):
print(item['id'])
print(item['title'])
But I not 100% sure the route to go. Hope someone can assist me. Still learning. I know how to save to the model I just need help with getting the data needed.

In fact this looks like a comma separated list of JSON blobs. We can convert this to a list as follows:
from json import loads as jsonload
data = jsonload('[{}]'.format(request.POST[manager_type_item]))
These are JSON blobs, so we can decode these with json.loads, and then process these, like:
for itm in data:
Tag.objects.create(**itm)
or in case the dictionaries contain other elements that do not belong to the model:
for itm in data:
Tag.objects.create(id=itm['id'], title=itm['title'])
We thus use a mapping to convert these JSON blobs first to there relevant vanilla Python objects (here dictionaries that map strings to strings), and then turn the given elements into a Tag (or something else).
Or in bulk:
Tag.objects.bulk_create([Tag(**itm) for itm in data])

Related

How do you access multi-dimensional arrays of objects in JavaScript?

I need to access JavaScript objects stored in a multi-dimensional array. The data is being exported by a WordPress plug-in. Note, I cannot change the code to use a single array.
There are two arrays named "employees". Is this array format compatible with JavaScript? The JSON export was intended for PHP processing.
(Note, The code below is a simplified model to illustrate the issue).
var data = '{"employees":[{"firstName":"John0"}, {"firstName":"Anna0"},{"firstName":"Peter0"}],"employees":[{"firstName":"John1"}, {"firstName":"Anna1"},{"firstName":"Peter1"}]};';
var json = JSON.parse(data);
document.querySelector('#test').innerHTML = json.employees[2].firstName;
Here it is on JSFiddle:
https://jsfiddle.net/2524fhf4/11/
How for example, would one access the value "Peter0" in the first array? In a single array, it would be accessed like this:
var result = json.employees[2].firstName;
It appears to me that in this format it is only possible to access the last array.
It appears to me that in this format it is only possible to access the
last array.
Because when your object literal has two (or more) keys of the same name, last one will override the rest of them.
Check this demo
var data = '{"employees":[{"firstName":"John0"}, {"firstName":"Anna0"},{"firstName":"Peter0"}],"employees":[{"firstName":"John1"}, {"firstName":"Anna1"},{"firstName":"Peter1"}]}';
console.log(JSON.parse(data)); //it will only display first one
In the above example, you can see that there is only one key of the data

recursively parse json in javascript to retrieve certain keys' values

I am new to javascript and every time i try learning it, I just end up in an immense amount of frustration and disgust ! No offense, but this is my opinion or perhaps I am too stupid to not understand how it works at all.
I have a simple requirement. I have a pretty deeply nested dictionary (which is what it is called in many backend languages) at hand. To be more specific it is the raw text of a postman collection. The collection itself could have multiple nested directories.
Now all I want to do is to be able to parse this dictionary and do something with it recursively.
For example, if I had to do the same in python I would do it as simply as :
def createRequests(self, dic):
total_reqs = 0
headers = {}
print type(dic)
keys = dic.keys()
if 'item' in keys:
print "Folder Found. Checking for Indivisual request inside current folder . . \n"
self.item_list = dic.get('item')
for each_item in self.item_list:
self.folder.append(self.createRequests(each_item))
else:
print "Found Indivisual request. Appending. . . \n"
temp_list = []
temp_list.append(dic)
self.requestList.append(temp_list)
return self.requestList
where dic would be my dictionary that I want to parse.
Is there any simple and straight forward way to do the same in Javascript?
Let's just say all I want to do is that if I have a text file that has properly formed json data in it and whose contents have been read into dataReadFromFile and then it has been converted into a JSON as :
var obj = JSON.parse(dataReadFromFile);
is there any simple and easy way to convert this JSON to dictionary or the dataReadFromFile directly into a dictionary such that I can say something like dictioanry.keys() if I wanted a list of the keys in it.
Note that the content of the file is not fixed. It may have multiple levels of nesting, which may not be known beforehand.

Javascript array/object order from associative PHP array

Before I describe the issue, please forgive any incorrect terms and accidental references to objects instead of arrays and vice-versa, I'm not completely up to speed on this but working my way through it.
I have the following array in PHP saved as a session variable:
{"CategoryF":[],"CategoryA":["Life","There","People","Land","Family"],"CategoryC":["Various"]}
After a thumbnail in a grid of images is dragged into a new order, it execute a function in javascript and makes a call to a PHP script using ajax. It currently only retrieves the most up to date version of a session array. It will later progress to make the necessary steps to save the updated array back to session variable and database:
var sorty = Sortable.create(thumbcontainer, {
animation: 250,
draggable: "img",
dataIdAttr: 'id',
onUpdate: function (/**Event*/evt) {
var orderList = sorty.toArray();
var catsArray =
$.ajax({
type: 'POST',
url: 'includes/proc_cats.php',
dataType: 'json'
}).done(function(returnedCatsArray) {
console.log(returnedCatsArray);
});
console.log('Dragged. Order is: ' + orderList);
}
});
proc_cats.php
<?php
// Access the existing session
session_start();
// $catsArray is a session variable, in the format as above.
$catsArray = json_encode($_SESSION['categoriesPics']);
echo $catsArray;
?>
The var orderList will produce a string with the order of each thumbnail by id, separated by comma: '42,35,95,12,57'.
The console shows the PHP array as a javascript array fine but in a different order. I want to be able to insert the string containing the orders into the array and save it back into the database. It will associate with its relevant category, similar to:
{"CategoryF":[],"CategoryA":["Life":["23,74,47,12,86,83,12"],"There","People","Land","Family"],"CategoryC":["Various"]}
But can't lose the order as other parts of the site reference the array by indices using array_keys. The console produces:
Object:
CategoryA:Array[0]
CategoryC:Array[0]
CategoryF:Array[5]
Have I missed something? I believe that the overall array is an object rather than an array because it didn't have any index whereas the subcategories did and they get presented as an array. array_keys in PHP have made it straightforward enough to work around any indexing problems up until now on the PHP side in other areas of the site but I'm wondering if the solution for the javascript side is something as straightforward? The subcategories currently have indices only because I've yet to associate and orderList with them so I'm not trying not to backtrack and build an index for the array as it's going to get difficult (unless there's a simple way to do this that I've overlooked).
(This is a more specific version of a question I asked an hour ago that I've now deleted for being too broad).
I believe you have a slight confusion based on the terms 'associative array' and 'array'. A php associative array corresponds to a javascript object. returnedCatsArray should be accessed similar to $catsArray. ie. with keys. If one of those keys returns an an actual array, you can then index into it.
php array_keys would be Object.keys(returnedCatsArray) in javascript.
From further research it appears this is just not doable. So the best way to do this may be to provide an order array alongside my category array.
If I add the additional code of:
$parentCatOrder = array_keys($catsArray);
in my proc_cats.php script I have a concise way of generating an index reference for my original array on the fly each time. This produces an array similar to:
$parentCatOrder = {'categoryF', 'categoryA', 'categoryC'};
which has an index that I can refer to that keeps its order. So $parentCatOrder[2] will always produce 'categoryC' unless I've changed the array myself.
I then return both arrays to javascript using the following:
$return_data['catsarray'] = $catsArray;
$return_data['parentcatsorder'] = $parentCatOrder;
// Encode it back into a JSON object before sending
echo json_encode($return_data);
In javascript I can reference returnedCatsArray.catsarray[returnedCatsArray.parentcatsorder[1]][3] if I'm working with an index of 1-3 and guarantee this will produce the same result for every user unless the array has been changed by the user.

Get Data from Text File to Multidimensional Array Javascript

I have a little bit of an issue with a JavaScript function that needs to read data from a TextFile (something JS is already limited with) and then process tha TextFile data into a MultiDimensional Array (another thing that JS doesn't nativelly suport).
With that in mind, I have a text file in this format:
1, Name, Data, Serial
2, Name, Data, Serial
3, Name, Data, Serial
And so on.
So, the objective is to get that same data and put it, like that, into an array.
I suppose that, from what I've been reading, I need an Array of an Array, segmenting the first one by lines [/n] and the second one by commas [,]. However, given the "by-default" limitations, I'm very confused at this point. I do suppose I need jQuery, however.
I tried this:
var fs = require('fs');
var array = fs.readFileSync('file.txt').toString().split("\n");
for(i in array) {
var array = fs.readFileSync('file.txt').toString().split(",");
for(f in array) {
}
}
With little success, because then I don't really know how to store it, the objective being a Multidimensional Array that Replicates the Format of the text file, so latter it could be used to search by index or instance following an user input to get results.
I really appreciate any help.
At first glance it seems like you are trying to read in a CSV file. If that is indeed the case I recommend node-csv:
http://www.adaltas.com/projects/node-csv/
https://github.com/wdavidw/node-csv
This helped me reading file to JavaScript, however this example converts retrieved data to JSON. Just looking at the format of your text file, I would assume a JSON string or Javascript object would work with your data.
Example convert to JSON
With JSON and JS objects, instead of referencing a array indexes eg. array[i][x]. you would replace [x] with .propertyName
data = {
"id": 1,
"name": "Fred"
};
//access data like this
data[i].name //will return "Fred" as i =0
to create JS object, just initialize array properties without the ""(quotation marks). accessing JS and JSON properties are done in the same way, main advantage over a multidimensional array is that you can reference an actual property name, as opposed to indexes.

How should i save the response data in a object(json) to have better manipulation and performance?

what i am doing is:
1. Get values from ajax response(which is in json format) for listing rows of data which
response = {"categories":[{"name":"General","id":"6305","pop":"show when clicked"},{"name":"Navigation","id":"6043","pop":"show when clicked"},{"name":"New","id":"6051","pop":"show when clicked"},{"name":"Time","id":"6117","pop":"show when clicked"},{"name":"Reesh","id":"6207","pop":"show when clicked"}]}
2 . I will parse the json and store in a object like this
ex:
object= {6305:{"name":"General","id":"6305","pop":"show when clicked"},
6043:{"name":"Navigation","id":"6043","pop":"show when clicked"},
6051:{"name":"New","id":"6051","pop":"show when clicked"},
6117:{"name":"Time","id":"6117","pop":"show when clicked"},
6207:{"name":"Reesh","id":"6207","pop":"show when clicked"}};
why i am doing this is because i can get the data using the id
ex: object[6305] will give me the data.
3 .So that i can retrieve the data and also make changes to values in the object using the id when changes occur in db.
ex: object[6350].pop="changed";
Please tell me:
-->whether is this the correct method or i can do it in a much simpler or efficient way?
-->whether i can store the json response as it is and parse data as it is? if so please explain with example.
Yes, of course you would not need to build the object:
function getObject(id) {
for (var i=0; i<response.categories.length; i++)
if (response.categories[i].id == id)
return response.categories[i];
return null;
}
However, if you often need to access objects by their ids this function would be slow. Creating the lookup table as you did will not create much memory overhead, but make retrieving data much faster.
BTW: Your title question "save data as object or json" is confusing. Serializing manipulated objects back to JSON makes no sense, as you always will use the parsed objects. Of course, if you just needed to manipulate a JSON string, and knew exactly what to do, (simple) string manipulation could be faster than parsing, manipulating and stringifying.

Categories

Resources