How to order descending JSON content [closed] - json.net

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I'm trying ordering JSON data based on column called "Priority".
Follow JSON Content Partial:
{
"Threads":
{
"Program1" :
{
"Filepath": "C:\\ProgramFiles(x86)...",
"Priority": 0
},
"Program2" :
{
"Filepath": "C:\\ProgramFiles(x86)...",
"Priority": 1
}
}}
Expected:
{
"Threads":
{
"Program2" :
{
"Filepath": "C:\\ProgramFiles(x86)...",
"Priority": 1
},
"Program1" :
{
"Filepath": "C:\\ProgramFiles(x86)...",
"Priority": 0
}
}}
Tried the code below but throw error:
JObject jsonFile = JObject.Parse(JSONContent);
var sortedObject = new JObject(jsonFile["Threads"].OrderByDescending(obj => (int) obj["Priority"] ) ); #<= Throw error.
Any idea to solve this solution?

Managed to get it working using JObject but it's not pretty:
var json = "{\r\n\"Threads\": \r\n{\r\n \"Program1\" : \r\n {\r\n \"Filepath\": \"C:\\\\ProgramFiles(x86)...\",\r\n \"Priority\": 0\r\n },\r\n \"Program2\" : \r\n {\r\n \"Filepath\": \"C:\\\\ProgramFiles(x86)...\",\r\n \"Priority\": 1\r\n },\r\n \"Program3\" : \r\n {\r\n \"Filepath\": \"C:\\\\ProgramFiles(x86)...\",\r\n \"Priority\": 3\r\n }\r\n}}";
var obj = JObject.Parse(json);
var threads = (JObject)obj["Threads"];
var sortedObj = new JObject(
threads.Properties().OrderByDescending(p => (int)p.Value["Priority"])
);
Console.WriteLine(sortedObj.ToString(Formatting.Indented));

Related

How to generate a pdf as a result of HTTP request firebase function? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
How to generate a pdf as a result of HTTP request firebase function with pdfmake?
Let's say I have the following JSON
{
"user" : "John Doe",
"booksOwned":[
{
"title":"Fancy Coffins to Make Yourself",
"author":"Dale L. Power"
},
{
"title":"Knitting With Dog Hair",
"author":"K Crolius"
},
{
"title":"Everything I Want to Do is Illegal",
"author":"Joel-Salatin"
}
]
}
And I want a PDF that greets the User and lists all books in a table. This should be the result when I call a firebase function with this JSON.
How can I do this with pdfmake?
first install pdfmake
npm install pdfmake
and use this following function, notice that you have to ajust the docDefinition for your needs
exports.getPDF = functions.https.onRequest(async (req, res) => {
//...
var data = JSON.parse(req.query.json); //asume json is given as parameter
//fonts need to lay in the functions directory
var fonts = {
Roboto: {
normal: './fonts/Roboto-Regular.ttf',
bold: './fonts/Roboto-Medium.ttf',
italics: './fonts/Roboto-Italic.ttf',
bolditalics: './fonts/Roboto-MediumItalic.ttf'
},
};
var PdfPrinter = require('pdfmake'); //needs to installed via "npm install pdfmake"
var printer = new PdfPrinter(fonts);
var docDefinition ={
content: [
{text: 'Hello User:', style: 'header'},
{
table: {
body: [
['book', 'author',],
['book1','author1'],
['book2','author2'],
['book3','author3']
]
}
}
]
}
var options = {
// ...
}
var pdfDoc = printer.createPdfKitDocument(docDefinition, options);
pdfDoc.pipe(res.status(200));
pdfDoc.end();
});

Pacts: Matching rule for non-empty map (or a field which is not null) needed

I need help with writing my consumer Pacts using pact-jvm (https://github.com/DiUS/pact-jvm).
My problem is I have a field which is a list (an array) of maps. Each map can have elements of different types (strings or sub-maps), eg.
"validatedAnswers": [
{
"type": "typeA",
"answers": {
"favourite_colour": "Blue",
"correspondence_address": {
"line_1": "Main St",
"postcode": "1A 2BC",
"town": "London"
}
}
},
{
"type": "typeB",
"answers": {
"first_name": "Firstname",
"last_name": "Lastname",
}
}
]
but we're only interested in some of those answers.
NOTE: The above is only an example showing the structure of validatedAnswers. Each answers map has dozens of elements.
What we really need is this: https://github.com/pact-foundation/pact-specification/issues/38, but it's planned for v.4. In the meantime we're trying a different approach. What I'm attempting to do now is to specify that each element of the list is a non-empty map. Another approach is to specify that each element of the list is not null. Can any of this be done using Groovy DSL?
This:
new PactBuilder().serviceConsumer('A').hasPactWith('B')
.port(findAvailablePort()).uponReceiving(...)
.willRespondWith(status: 200, headers: ['Content-Type': 'application/json'])
.withBody {
validatedAnswers minLike(1) {
type string()
answers {
}
}
}
doesn't work because it mean answers is expected to be empty ("Expected an empty Map but received Map( [...] )", see also https://github.com/DiUS/pact-jvm/issues/298).
So what I would like to do is something like this:
.withBody {
validatedAnswers minLike(1) {
type string()
answers Matchers.map()
}
}
or:
validatedAnswers minLike(1) {
type string()
answers {
keyLike 'title', notNull()
}
}
or:
validatedAnswers minLike(1) {
type string()
answers notNull()
}
Can it be done?
I would create two separate tests for this, one test for each of the different response shapes and have a provider state for each e.g. given there are type b answers.
This way when you verify on provider side, it will only send those two field types.
The union of the two examples gives a contract that allows both.
You can do it without DSL, sample Groovy script:
class ValidateAnswers {
static main(args) {
/* Array with some samples */
List<Map> answersList = [
[
type: 'typeA',
answers: [
favourite_colour: 'Blue',
correspondence_address: [
line_1: 'Main St',
postcode: '1A 2BC',
town: 'London'
]
]
],
[
type: 'typeB',
answers: [
first_name: 'Firstname',
last_name: "Lastname"
]
],
[
type: 'typeC',
answers: null
],
[
type: 'typeD'
],
[
type: 'typeE',
answers: [:]
]
]
/* Iterating through all elements in list above */
for (answer in answersList) {
/* Print result of checking */
println "$answer.type is ${validAnswer(answer) ? 'valid' : 'not valid'}"
}
}
/**
* Method to recursive iterate through Map's.
* return true only if value is not an empty Map and it key is 'answer'.
*/
static Boolean validAnswer(Map map, Boolean result = false) {
map.each { key, value ->
if (key == 'answers') {
result = value instanceof Map && value.size() > 0
} else if (value instanceof Map) {
validAnswer(value as Map, false)
}
}
return result
}
}
Output is:
typeA is valid
typeB is valid
typeC is not valid
typeD is not valid
typeE is not valid

Query in Firebase by value of childs [duplicate]

This question already has answers here:
Firebase search by child value
(2 answers)
Closed 3 years ago.
{
"users" : {
"1320104182" : {
"datas" : {
"bio" : "some_data",
"picture" : "some_data",
"username" : "some_data",
"website" : "some_data",
"followers" : 14,
}
},
"3271376571" : {
"datas" : {
"bio" : "some_data",
"picture" : "some_data",
"username" : "some_data",
"website" : "some_data",
"followers" : 10,
}
}
}
}
I'm new to Firebase and i'm trying to do multiple think here without any success so far.
How can i retrieve a user by his "username" without knowing the key ?
Or how can i order the users by followers ?
I tried everything i could find in the documentation for a few hours i'm desperate.
This seems fairly easy:
var ref = firebase.database().ref("users");
var query = ref.orderByChild("database/username").equalTo("some_data");
query.once("value", function(snapshot) {
snapshot.forEach(function(child) {
console.log(child.key, child.val().bio);
});
});
Firebase is not so good when you need fancy queries. You must handle everything in your client (JavaScript) which is not the best approach when dealing with large data. In this case, I'd suggest you something like this:
const nameToSearch = 'John';
firebase.ref('users').once('value') //get all content from your node ref, it will return a promise
.then(snapshot => { // then get the snapshot which contains an array of objects
snapshot.val().filter(user => user.name === nameToSearch) // use ES6 filter method to return your array containing the values that match with the condition
})
To order by followers, you can either also apply sort() (see example 1) or any of firebase default methods orderByChild() (see example 2), orderByKey (see example 3), or orderByValue (see example 4)
Example 1:
firebase.database().ref("users").once('value')
.then(snapshot => {
const sortedUsers = snapshot.sort((userA, userB) => {
if (userA.name < userB.name) {
return -1;
}
if (userA.name > userB.name) {
return 1;
}
return 0;
})
})
Example 2:
var ref = firebase.database().ref("dinosaurs");
ref.orderByChild("height").on("child_added", function(snapshot) {
console.log(snapshot.key + " was " + snapshot.val().height + " m tall");
});
Example 3:
var ref = firebase.database().ref("dinosaurs");
ref.orderByKey().on("child_added", function(snapshot) {
console.log(snapshot.key);
});
Example 4:
var scoresRef = firebase.database().ref("scores");
scoresRef.orderByValue().limitToLast(3).on("value", function(snapshot) {
snapshot.forEach(function(data) {
console.log("The " + data.key + " score is " + data.val());
});
});
Note: there might be typos in the examples, I wrote just to show you the idea of the concepts.
Check the following docs for more info:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
https://firebase.google.com/docs/reference/js/firebase.database.Query#orderByChild
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
Hope it helps

Fetching denormalized data with firebase, angularFire

I'm trying to fetch all flowers data which belongs to a certain user, in this case simplelogin:69.
I'm starting with fetching all flower keys from the user, like this:
/users/simplelogin:69/flowers/
var ref = new Firebase("https://URL.firebaseio.com/users/"+uid+"/flowers");
var sync = $firebase(ref);
Now im stuck figuring out a clean way to fetch all the flower data by looping thrue every flower key from simplelogin:69 without looping thrue EVERY key in /flowers/ (in example below i only have three flower keys but in production i might have 10k).
I tried FirebaseIndex and firebase-util, but can't get it to work properly. Do anyone have any tips or anything? I've read previous posts here on stack but most seems out of date or not really suited for what im going for. Would really appriciate anything that can be solved with AngularFire.
Kind regards,
Elias
{
"flowers" : {
"-JiU57sFAfQwYtIq-LCl" : {
"image" : "test",
"name" : "test",
"type" : "Roses",
"uid" : "simplelogin:69"
},
"-JiU9-3ajlnFLpyUmBvL" : {
"image" : "dasdasd",
"name" : "sadasdas",
"type" : "Roses",
"uid" : "simplelogin:69"
},
"-JiUF-mioK3jQCYy6ZiG" : {
"image" : "ss",
"name" : "ss",
"type" : "Lilies",
"uid" : "simplelogin:69"
}
},
"users" : {
"simplelogin:69" : {
"flowers" : {
"-JiU57sFAfQwYtIq-LCl" : true,
"-JiU9-3ajlnFLpyUmBvL" : true,
"-JiUF-mioK3jQCYy6ZiG" : true
}
},
"simplelogin:70" : {
},
"simplelogin:71" : {
}
}
}
Got it to work now, thanks to #Kato 's answer on thread:
Firebase data normalized. How should I fetch a collection based on this structure? (tried it before creating this thread but didnt get it to work, so made som small changes and now it works).
Posting the solution for anyone stubling upon the same situation:
$scope.flowers = {};
var flowerRef = new Firebase('https://URL.firebaseio.com/flowers/');
var keyRef = new Firebase('https://URL.firebaseio.com/users/'+checkAuth.auth.uid+'/flowers');
keyRef.on('child_added', function(snap) {
var flowerId = snap.key();
flowerRef.child(flowerId).on('value', function(snap) {
$timeout(function() {
if( snap.val() === null ) {
delete $scope.flowers[flowerId];
}
else {
$scope.flowers[flowerId] = snap.val();
}
});
});
});
keyRef.on('child_removed', function(snap) {
var flowerId = snap.key();
$timeout(function(snap) {
delete $scope.flowers[flowerId];
});
});
This really is a tough issue with Firebase. If you implement a custom factory object for the user's flower list, you could dynamically request new flower data as the list changes.

Jquery Datatables Ajax Response

I am trying to follow the datatable example for Ajax data source (objects) found here. I am using asp.net and have the following handler which receives my data, processes it and provides the response.
public class UsersHandler : IHttpHandler
{
private const string JsHeader = #"{{""data"" {0}}}";
public void ProcessRequest(HttpContext context)
{
IEnumerable<SystemUser> data = SystemUserLogic.LoadAllSystemUsers();
List<SimpleUser> userlist = new List<SimpleUser>();
foreach (SystemUser su in data)
{
SimpleUser simple = new SimpleUser();
simple.Id = su.Id;
simple.FullName = su.NameFirst;
simple.Email = "example#email.co.uk";
userlist.Add(simple);
}
string json = JsonConvert.SerializeObject(userlist, Formatting.Indented);
context.Response.ContentType = "text/plain";
context.Response.ContentEncoding = Encoding.UTF8;
context.Response.Cache.SetNoStore();
context.Response.Expires = -1;
context.Response.Write(String.Format(JsHeader, json));
}
which deliveries the correct response when I catch it in the browser and look at the data via the network traffic. My aspx page contains the following.
$('#table_id').DataTable({
"ajax": '/Handlers_New/UsersHandler.ashx',
"columns": [
{ "data": "Id" },
{ "data": "FullName" },
{ "data": "Email" },
{ "data": "KeyResource" }
]
});
However when the page loads, I am getting this error:
DataTables warning: table id=table_id - Invalid JSON response. For more information about this error, please see http://datatables.net/tn/1
The outputted data looks like this,
{"data" [
{
"Id": 1,
"FullName": "Admin",
"Email": "example#email.co.uk",
"KeyResource": false
},
{
"Id": 2,
"FullName": "Jon",
"Email": "example#email.co.uk",
"KeyResource": false
},
{
"Id": 3,
"FullName": "Stephen",
"Email": "example#email.co.uk",
"KeyResource": false
}, etc.....
Please tell me why I am getting this error. Should I be manipulating the json object differently, or am I missing something with the Jquery datatables?
I have managed to fix my issue amazingly due to jsonlint. I ran my code through that and it turns out I was missing a ':' in my jsHeader. So what I had was:
private const string JsHeader = #"{{""data"" {0}}}";
and what I have now which now works is:
private const string JsHeader = #"{{""data"": {0}}}";
Hope this helps any one else encountering a similar issue.

Resources