Get one to may relationship data from tables as JSON - json

I have this two tables from the diagrams.For every question i can have multiple answer.
I want to get data by question id in json format like this:
var initialData = [
{question_id: "1", Description: "Danny", Status: "1", answers: [
{ answer_id: "1", description: "AAAAA" },
{ answer_id: "2", description: "Bbbbb" }]
}
];
I use this code
var question = db.Questions.FirstOrDefault((p) => p.questionID== id);
return this.Json(question , JsonRequestBehavior.AllowGet);
and i get this
var initialData = [
{question_id: "1", Description: "Danny", Status: "1", answers:null
}
];
Can you help my please with a solution.

Can you try this please.
var question = db.Questions.Include("Answer").FirstOrDefault((p) => p.questionID== id);
Have a look at the ado.Net blog

Related

Access to a element of array value in json from dart

I have this const variable in flutter:
static const questions = [
{
"question": "question",
"answers": ["1", "2"],
"message":
"message",
},
]
how to access to "1" from dart??
I try using QuestionContent.questions[0]["answers"][0].
But I got error "The method '[]' can't be unconditionally invoked because the receiver can be 'null'"
Try use:
Text((QuestionContent.questions[0] as Map<String, dynamic>)['answers'][0] ?? '')
or:
Text((questions[0]['answers'] as List<String>)[0]),
Try code below:
const questions = [
{
"question": "question",
"answers": ["1", "2"],
"message":
"message",
},
];
Map<String, Object> question = questions[0];
List<String> answers = question["answers"] as List<String>;
String firstAnswer = answers.elementAt(0);
The reason you get the error is the compiler could not tell whether your QuestionContent.questions[0]["answers"] is null or not:

How to get data of a JSON file (typescript)

Hi I got a bit stuck at trying to understand how to fetch data of a JSON file.
environment.ts:
export const environment = {
production: false,
urlListBooks: "/assets/list-books.json",
urlGetBooks: "/assets/edit-book.json?:id",
urlGetTags: "/assets/edit-book.json?:tags",
urlPostBooks: "/assets/edit-book.json",
urlListTags: "/assets/list-tags.json",
urlPostTags: "/assets/edit-tag.json"
};
edit-book.json:
"book":{
"id": 1,
"title": "The Shining",
"authorId": 1,
"tags": [{"name":"new"}, {"name":"test"}]
},
"authors":[
{
"id": 1,
"prename": "Stephen",
"surname": "King"
},
{
"id": 3,
"prename": "Algernon",
"surname": "Blackwood"
},
{
"id": 4,
"prename": "Edgar Allan",
"surname": "Poe"
},
{
"id": 5,
"prename": "Howard Phillips",
"surname": "Lovecraft"
}
],
"tags":[
{
"name": "new"
},
{
"name": "Horror"
},
{
"name": "Romance"
}
]
}
service:
getBookTags(n: String) Observable<Tag[]>{
return this.http.get<Tag[]>(environment.urlGetTags.)
}
what I want getBookTags(n: String) to do is returning the tags array of the book with title n defined in the edit-book.json (e.g. "tags": [{"name":"new"}, {"name":"Horror"}] ) so that I can later use the function to check which tags a book has and select them.
Your help would be very appreciated :)
Ok I think I've solved this for you, I'm going to walk through my process with you so you understand what the goal is. You can see my solution here: https://codesandbox.io/s/thirsty-minsky-g6959f?file=/assets/edit-book.json:0-752
First thing is that your JSON you provided doesn't really make much sense, it shows multiple authors and just one "book". I think instead you want multiple books. Secondly, it's gotta be wrapped in a curly brace as shown:
{
"books": [
{
"id": 1,
"title": "The Shining",
"authorId": 1,
"tags": [{ "name": "new" }, { "name": "test" }]
},
{
"id": 2,
"title": "The Wendigo",
"authorId": 2,
"tags": [{ "name": "Horror" }]
}
],
"authors": [
{
"id": 1,
"prename": "Stephen",
"surname": "King"
},
{
"id": 3,
"prename": "Algernon",
"surname": "Blackwood"
},
{
"id": 4,
"prename": "Edgar Allan",
"surname": "Poe"
},
{
"id": 5,
"prename": "Howard Phillips",
"surname": "Lovecraft"
}
],
"tags": [
{
"name": "new"
},
{
"name": "Horror"
},
{
"name": "Romance"
}
]
}
Now, in your Typescript code we want to have typings for the json you're going to fetch. This will make your code more readable, it will give you intellisense, and help you catch some errors before you try to run your code. So we are going to go ahead and type the properties of the JSON as follows:
type Tag = {
name: string;
};
type Book = {
id: number;
title: string;
authorId: number;
tags: Tag[];
};
type Author = {
id: number;
prename: string;
surname: string;
};
type BookData = {
books: Book[];
authors: Author[];
tags: Tag[];
};
Basically what I said is we have bookdata which is made up of books, authors, and tags. Books have properties given under type Book, same thing with Author and Tag.
Now for the actual running code, we are going to use the fetch api to get the json data at the url.
async function getBookTags(n: string): Promise<Book[]> {
return fetch(url)
.then<BookData>((res) => res.json())
.then((data) => data.books)
.then((books) => books.filter((b) => doesBookHaveTag(b, n)));
}
First thing we do is fetch the data from the api, this returns a promise which when resolved (this is what .then does) we take the response and parse it for a json. Then when that promise resolves we get the books in the data. Then when that promise resolves we filter in books that have the matching tag.
doesBookHaveTag is just a little helper function I defined:
function doesBookHaveTag(book: Book, n: string): boolean {
// just return if book has at least one tag matching n
return book.tags.some((t) => t.name.toLowerCase() === n.toLowerCase());
}
If you don't understand promises you should watch some videos on it, but basically the browser sends out an http request and then when it resolves it queues a task to execute the function [see endnote] in .then when it has time. So when we want to call your async function and say log all books with the tag "horror" we do it as shown:
getBookTags("horror").then(console.log); // returns the one book.
I hope this makes sense and you can sort of see how to fetch the data, how to handle the promise it returns, and how to type your response. The only thing I'm not sure on is how Angular changes this for you (I'm a react guy), but this is really just non-library specific Javascript/Typescript.
[endnote] when I say function in .then, what I mean is that .then(data => data.books) is passing a function into the .then function. data => data.books is actually a function the same as:
function(data: BookData): Book[] {
return data.books
}

JSON Query with wildcard?

I am new with JSON Query, trying to do a simple task but I could not find a solution online that I got working.
I have a json document like this:
[ {
"folder" : "User/Admin/UserA",
"User" : "Linda"
},
{
"folder" : "User/Service/UserB",
"User" : "John"
},
{
"folder" : "User/Admin/UserC",
"User" : "Peter"
} ]
I want to get all array elements under User/Admin/.
This Query gets me one result $..[?(#.folder==["User/Admin/UserA"])]
how can I make it more dynamic with a wildcard like $..[?(#.folder==["User/Admin/*"])]?
Tested with https://www.jsonquerytool.com/
Thank you for any help
you can use SelectToken with LINQ and Contains. For more complicated search you can use .StartsWith or .EndWith too.
var json = "...your json";
var jsonArr = JArray.Parse(json);
var users = jsonArr.ToArray()
.Where(m => m.SelectToken("folder").ToString().Contains("User/Admin/"))
.Select(u => u.SelectToken("User")).ToList();
result
Linda
Peter
or
var usersFolders = jsonArr.ToArray()
.Where(m => m.SelectToken("folder").ToString().Contains("User/Admin/")).ToList();
result
"folder": "User/Admin/UserA"
"User": "Linda"
"folder": "User/Admin/UserC"
"User": "Peter"
With ~Q (disclosure: I'm the main developer):
https://github.com/xcite-db/Unquery
{
"#return:[]?folder starts_with 'User/Admin'": ["."]
}
Result:
[
{
"folder": "User/Admin/UserA",
"User": "Linda"
},
{
"folder": "User/Admin/UserC",
"User": "Peter"
}
]

Reactjs - How to create a JSON with list Child Object?

I have JSON structure like this
"timebought": "2021-01-01T00:00:00",
"totalCost": 3000.0,
"address": "ABC",
"status": false,
"customersEmail":"nguyenvana#gmail.com",
"orderDetails": [
{
"productId": "A1",
"amount": 5
},
{
"productId": "A2",
"amount": 5
}
]
If I want make a JSON for post, how do i do it? I mean the child object "orderDetails", can you give me an example?
I found out how to do it:
First, make a function return list Child:
function toArr(){
let arr = [];
prodList.forEach((prod) => {
let item ={"id":prod.id,"amount" : prod.quantity};
arr = [...arr,item];
});
console.log(arr);
return arr;}
and then
const body = JSON.stringify({
customersEmail : e.target.email.value,
totalCost : totalCost.current,
status : false,
address: e.target.address.value,
orderDetails: toArr()
});

Mongoose query on json array

I am new to node.js and using mongoose along with node.js.
Schema:
var userSchema = new mongoose.Schema({
username: String,
password: String,
phone_no : String,
email: String,
name:String,
dob: {type: Date, "default": Date.now},
city:String,
locality:{lattitude:Number,longitude:Number},
sports: [String]
});
sample entry:
"userId": 10,
"username": "shu",
"name": "shubham goyal",
"password": "ahu",
"phone_no": "919357701457",
"email": "shubham2892#gmail.com",
"city": "delhi",
"_id": {
"$oid": "5331dbc243bb59f80a7ed60b"
},
"sports": [
"cricket,football"
],
"dob": {
"$date": "2014-03-25T19:40:50.886Z"
},
"__v": 0
}
The query i am trying to make:
models.user.find({'sports' : sports_selected},function(err,users) {
if(err) {
console.log("Cannot fetch sports with requested username" + req.user.username);
console.log(err);
}if(!users){
console.log("cannot find specified username" + req.user.username);
}else{
console.log(users.username);
//sport = player.sports;
//sport = ['cricket','football','basketball'];
}
});
I am getting undefined in users.username.I want to return all users who have selected a particular sports say 'cricket'.I googled it a lot but could not find anything.
It looks like your sample entry is incorrectly formatted. Sports entry shouldn't be like this:
"sports": [
"cricket,football"
]
You should keep the sports data like this instead:
"sports": [
"cricket","football"
]
If you provide cricket and football in the same string, mongo cannot differentiate these two as different sports.
Also users should be an array, so you need to loop through the array. Say you have one user with sport selected as cricket, then you can print users[0].username