JSON.parse error on simplejson return in Django - django

I have a view page that currently has two columns of data shown, soon to be expanded to four. Each column contains the result of a QuerySet for that particular model.
Here's what I have in my views.py method:
if request.REQUEST["type"] == "text":
client = Client.objects.get(client_name = request.REQUEST["search"])
peerList = ClientPeers.objects.prefetch_related().filter(client = client.client)
compList = ClientCompetitors.objects.prefetch_related().filter(client = client.client)
else:
peerList = ClientPeers.objects.prefetch_related().filter(client = request.REQUEST["search"])
compList = ClientCompetitors.objects.prefetch_related().filter(client = request.REQUEST["search"])
for peer in peerList:
peerlst.append({"pid" : peer.parentorg.parentorg, "pname" : peer.parentorg.parentorgname})
for comp in compList:
complst.append({"cid" : comp.parentorg.parentorg, "cname" : comp.parentorg.parentorgname})
lst.append(simplejson.dumps(peerlst))
lst.append(simplejson.dumps(complst))
return HttpResponse(simplejson.dumps(lst), mimetype = "text/json")
This allows me to send a 2D array of data to the browser in the format
[ { //JSON }, { //JSON } ]
In my jQuery.ajax success function, I have
function handler(results) {
var data = JSON.parse(results);
for (var i = 0; i < data[0].length; i++)
$("#available_peers").append("<li>" + data[0][i].pname + "</li>");
for (var i = 0; i < data[1].length; i++)
$("#available_competitors").append("<li>" + data[1][i].cname + "</li>");
Firebug shows that the GET request works and I can see the data in the response tab. However, the console prints out
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data
var data = JSON.parse(results)
This error disappears if I replace var data = JSON.parse(results) with
var peers = JSON.parse(data[0]);
var comps = JSON.parse(data[1]);
Why does one method work but another doesn't?

The jQuery ajax() call will make an intelligent guess as to the returned data type. In your example, function handler(results), the results variable will already be a decoded JSON object, containing two items in an array. The reason that JSON.parse(data[0]) works, is that you have returned JSON encoded data as a string.
Don't encode the individual list elements to JSON before placing in the output array:
lst.append(peerlst) # <-- Don't encode to JSON string here
lst.append(complst)
return HttpResponse(simplejson.dumps(lst), mimetype = "application/json") # <-- Single JSON encoding

Related

django filter data and make union of all data points to assignt to a new data

My model is as follows
class Drawing(models.Model):
drawingJSONText = models.TextField(null=True)
project = models.CharField(max_length=250)
Sample data saved in drawingJSONText field is as below
{"points":[{"x":109,"y":286,"r":1,"color":"black"},{"x":108,"y":285,"r":1,"color":"black"},{"x":106,"y":282,"r":1,"color":"black"},{"x":103,"y":276,"r":1,"color":"black"},],"lines":[{"x1":109,"y1":286,"x2":108,"y2":285,"strokeWidth":"2","strokeColor":"black"},{"x1":108,"y1":285,"x2":106,"y2":282,"strokeWidth":"2","strokeColor":"black"},{"x1":106,"y1":282,"x2":103,"y2":276,"strokeWidth":"2","strokeColor":"black"}]}
I am trying to write a view file where the data is filtered based on project field and all the resulting queryset of drawingJSONText field are made into one data
def load(request):
""" Function to load the drawing with drawingID if it exists."""
try:
filterdata = Drawing.objects.filter(project=1)
ids = filterdata.values_list('pk', flat=True)
length = len(ids)
print(list[ids])
print(len(list(ids)))
drawingJSONData = dict()
drawingJSONData = {'points': [], 'lines': []}
for val in ids:
if length >= 0:
continue
drawingJSONData1 = json.loads(Drawing.objects.get(id=ids[val]).drawingJSONText)
drawingJSONData["points"] = drawingJSONData1["points"] + drawingJSONData["points"]
drawingJSONData["lines"] = drawingJSONData1["lines"] + drawingJSONData["lines"]
length -= 1
#print(drawingJSONData)
drawingJSONData = json.dumps(drawingJSONData)
context = {
"loadIntoJavascript": True,
"JSONData": drawingJSONData
}
# Editing response headers and returning the same
response = modifiedResponseHeaders(render(request, 'MainCanvas/index.html', context))
return response
I runs without error but it shows a blank screen
i dont think the for function is working
any suggestions on how to rectify
I think you may want
for id_val in ids:
drawingJSONData1 = json.loads(Drawing.objects.get(id=id_val).drawingJSONText)
drawingJSONData["points"] = drawingJSONData1["points"] + drawingJSONData["points"]
drawingJSONData["lines"] = drawingJSONData1["lines"] + drawingJSONData["lines"]

How can i send a Pagination-embed with a music list discord.js

I want send in a Pagination-embed with a music list because whan an embed is lower at 1024 letters it doesn't send.
I want send in many pages (4musics max per pages)
Sorry for my english, i'm french...
console.log(_serverQueue.songs)
let q = ``;
for(var i = 1; i < _serverQueue.songs.length; i++) {
q += `\n${i + 1}. **${_serverQueue.songs[i].title}**`;
}
let resp = [
{name: `Now Playing`, value: _serverQueue.songs[0].title},
{name: `Queue`, value: q},
];
//Putting it all together
const FieldsEmbed = new Pagination.FieldsEmbed()
.setArray({word: `Queue`})
.setAuthorizedUsers([message.author.id])
.setChannel(message.channel)
.setElementsPerPage(4)
.setPageIndicator(true)
.formatField('Playlist :', el => el.word)
FieldsEmbed.embed
.setColor('#008000')
.setTitle('Playlist :')
FieldsEmbed.build()
}
As per the Documentation of https://www.npmjs.com/package/discord-paginationembed
I explained the steps with Comments
const Discord = require('discord.js');
const Pagination = require('discord-paginationembed');
const songText = ["This is a long SongText", "That is Split up Over", "Multiple Sites", "End of Song"];
// The Splitting can happen via Discord.Js Util Class, it has a Splitter
const embeds = [];
for (let i = 1; i <= 4; ++i)
embeds.push(new Discord.MessageEmbed().setFooter('Page ' + i).setDescription(songText[i - 1]));
// Create Embeds here with the Content and push them into the Array
const myImage = message.author.displayAvatarURL();
new Pagination.Embeds()
.setArray(embeds)
.setAuthorizedUsers([message.author.id])
.setChannel(message.channel)
.setPageIndicator(true)
.setPage(1)
// Methods below are for customizing all embeds
.setImage(myImage)
.setThumbnail(myImage)
.setTitle('Test Title')
.setDescription('Test Description')
.setURL(myImage)
.setColor(0xFF00AE)
.build();

Gmail App search criteria

I have the following search criteria working very well in Gmail:
user#domain from:/mail delivery/ || /postmaster/ ||/Undeliverable/
I am trying to write Goole Apps code to return the same results. Here is the code:
var thread=GmailApp.search("user#domain from:/mail delivery/ || /postmaster/ ||/Undeliverable/ ");
I am getting different results. I am new to both Regex and Google Apps.
Try Amit Agarwal's tutorial on Gmail Search with Google Apps Script which includes Using Regular Expressions to Find Anything in your Gmail Mailbox:
function Search() {
var sheet = SpreadsheetApp.getActiveSheet();
var row = 2;
// Clear existing search results
sheet.getRange(2, 1, sheet.getMaxRows() - 1, 4).clearContent();
// Which Gmail Label should be searched?
var label = sheet.getRange("F3").getValue();
// Get the Regular Expression Search Pattern
var pattern = sheet.getRange("F4").getValue();
// Retrieve all threads of the specified label
var threads = GmailApp.search("in:" + label);
for (var i = 0; i < threads.length; i++) {
var messages = threads[i].getMessages();
for (var m = 0; m < messages.length; m++) {
var msg = messages[m].getBody();
// Does the message content match the search pattern?
if (msg.search(pattern) !== -1) {
// Format and print the date of the matching message
sheet.getRange(row,1).setValue(
Utilities.formatDate(messages[m].getDate(),"GMT","yyyy-MM-dd"));
// Print the sender's name and email address
sheet.getRange(row,2).setValue(messages[m].getFrom());
// Print the message subject
sheet.getRange(row,3).setValue(messages[m].getSubject());
// Print the unique URL of the Gmail message
var id = "https://mail.google.com/mail/u/0/#all/"
+ messages[m].getId();
sheet.getRange(row,4).setFormula(
'=hyperlink("' + id + '", "View")');
// Move to the next row
row++;
}
}
}
}

Alfresco WS Client API - WSSecurityException when using fetchMore method

Can someone tell me what's wrong with my code here... I'm always getting this exception on the first call to contentService.read(...) after the first fetchMore has occurred.
org.apache.ws.security.WSSecurityException: The security token could not be authenticated or authorized
// Here we're setting the endpoint address manually, this way we don't need to use
// webserviceclient.properties
WebServiceFactory.setEndpointAddress(wsRepositoryEndpoint);
AuthenticationUtils.startSession(wsUsername, wsPassword);
// Set the batch size in the query header
int batchSize = 5000;
QueryConfiguration queryCfg = new QueryConfiguration();
queryCfg.setFetchSize(batchSize);
RepositoryServiceSoapBindingStub repositoryService = WebServiceFactory.getRepositoryService();
repositoryService.setHeader(new RepositoryServiceLocator().getServiceName().getNamespaceURI(), "QueryHeader", queryCfg);
ContentServiceSoapBindingStub contentService = WebServiceFactory.getContentService();
String luceneQuery = buildLuceneQuery(categories, properties);
// Call the repository service to do search based on category
Query query = new Query(Constants.QUERY_LANG_LUCENE, luceneQuery);
// Execute the query
QueryResult queryResult = repositoryService.query(STORE, query, true);
String querySession = queryResult.getQuerySession();
while (querySession != null) {
ResultSet resultSet = queryResult.getResultSet();
ResultSetRow[] rows = resultSet.getRows();
for (ResultSetRow row : rows) {
// Read the content from the repository
Content[] readResult = contentService.read(new Predicate(new Reference[] { new Reference(STORE, row.getNode().getId(), null) },
STORE, null), Constants.PROP_CONTENT);
Content content = readResult[0];
[...]
}
// Get the next batch of results
queryResult = repositoryService.fetchMore(querySession);
// process subsequent query results
querySession = queryResult.getQuerySession();
}

URLEncode variable Parsing from String to Array as3

Ok! I have a flashVar variable that is coming into Flash, its URL encoded but I have already decoded it. My problem is I want the set of variables to be pushed into an array.
Let's say the variables are
"&text0=Enter Text...&size0=18&font0=Arial&color0=0&rotation0=0&y0=360&x0=640&text1=Enter
Text...&size1=18&font1=Arial&color1=0&rotation1=0&y1=360&x1=640"
and so on...
What I want is the variables to go into an array like
myArray[0].text = Enter Text...
myArray[0].size = 18]
myArray[0].font = Arial
myArray[0].color = 0
myArray[0].rotation = 0
myArray[0].y = 360
myArray[0].x = 640
myArray[1].text = ...........
.............................
.............................
myArray[n].text = ...........
I think there must be some way to do this. Most probably I'm thinking regular expression, but I'm pretty bad at regular expression. Please some help would be very very appreciated.
Thank You!
You don't have to decode your query string, just use the URLVariables object - it will do all the decoding for you. Then iterate over its dynamic properties to create your array. Use a RegExp to find the index numbers at the end of your variable keys:
function parseURLVariables( query:String ) : Array {
var vars:URLVariables = new URLVariables (query);
var arr:Array = [];
for (var key : String in vars) {
var splitIndex : int = key.search(/[0-9]+$/);
var name:String = key.substr (0,splitIndex);
var indexNumber:int = parseInt ( key.substr(splitIndex));
arr[indexNumber] ||= {};
arr[indexNumber][name] = vars[key];
}
return arr;
}
Since your query string starts with a an ampersand, you might have to use parseURLVariables ( myString.substr(1)), otherwise the URLVariables object will throw an error, complaining that the query string is not valid (it has to be url encoded, and start with a variable key).
you may use split method of string to something like this;
var astrKeyValue: Array = url.Split( "&" );
in this way each value in astrKeyValue is string keyvalue ( for example font1=Arial )
after than you may split each item with "=" and will get pair key and value ( for key - font1 and for value - arial)
so this code maybe will work for you
var str = "text0=Enter Text...&size0=18&font0=Arial&color0=0&rotation0=0&y0=360&x0=640&text1=Enter Text...&size1=18&font1=Arial&color1=0&rotation1=0&y1=360&x1=640"
var a : Array = str.split( "&" );
var newArr: Array = new Array()
for each ( var str1 in a )
{
var t: Array = str1.split( "=" );
newArr[ t[0] ] = t[1];
}
trace( newArr.text0 ) // -> Enter Text...
Here is a solution for you from me,
//your string data should be like this, there should be a seperate seperator (i've used pipe sign |) for each element which will be converted to an object and then pushed to the array
var strData:String = "text=Enter Text...&size=18&font=Arial&color=0&rotation=0&y=360&x=640|text=Enter Text...&size=18&font=Arial&color=0&rotation=0&y=360&x=640";
var myArray:Array = new Array();
var _tmpArr:Array = strData.split("|");
//populating the array
for(var i:int=0;i<_tmpArr.length;i++)
{
myArray.push(strToObj(_tmpArr[i]));
}
trace(myArray.length);
// coverts chunk of string to object with all key and value in it
function strToObj(str:String):Object
{
var obj:Object = new Object();
var tmpArr:Array = str.split('&');
for (var i:int = 0; i < tmpArr.length; i++)
{
var _arr:Array = String(tmpArr[i]).split('=');
var key:String = String(_arr[0]);
var val:String = String(_arr[1]);
obj[key] = val;
trace(key+" = "+val);
}
trace("----");
return obj;
}