I try to combine 2 tables of database to a json object, I think it is maybe a 3D array
like this↓
table_1 ->(name:"Ken"),(gender:"male")
table_2 ->(name:"Lon"),(gender:"male")
table_1 and 2 is 1st dimension, name and gender is 2nd dimension,
ken and male is 3rd dimension
so, I made a json object wiht PHP "json_encode()", and try to parse it with javascript
json object:
{
"client_infos":[ {
"client": {
"no": 1, "C_name": "ken", "input_date": "2017-07-20 13:44:46", "total_price": 123
}
,
"item_lists":[["item_list",
{
"no": 1, "rs_no": 1, "item_name": "ApplePie", "item_quantity": 2, "unit_price": 10
}
],
["item_list",
{
"no": 2, "rs_no": 1, "item_name": "BananaCow", "item_quantity": 3, "unit_price": 5
}
]]
}
,
{
"client": {
"no": 3, "C_name": "ken", "input_date": "2017-07-20 14:24:26", "total_price": 200
}
,
"item_lists":[["item_list",
{
"no": 5, "rs_no": 3, "item_name": "LimeMilk", "item_quantity": 5, "unit_price": 33
}
]]
}
]
}
how do I parse it ?
for example, I want to extract the data of 2nd client and item_lists.
I have been using JSON.parse(json), but I have no idea how to get the value.
var content = JSON.parse(res);
console.log(content.client_infos.client[1].no);
it's not work.
var object = JSON.parse(variableOrStringLiteral);
finally, I find out the right way to get the value that like this
var obj = JSON.parse(content);
obj.client_infos[0].client.no;
Related
JSON Object:
{
"students_detail": [
{
"student_id": 1,
"name": "abc",
"roll_number": 10
},
{
"student_id": 2,
"name": "pqr",
"roll_number": 12
}
],
"subject_details": [
{
"subject_id": 1,
"subject_name": "math"
},
{
"subject_id": 2,
"subject_name": "english"
}
],
"exam_details": [
{
"exam_id": 1,
"exam_name": "Prelim"
}
],
"mark_details": [
{
"id": 1,
"exam_id": 1,
"subject_id": 1,
"student_id": 1,
"mark": 51
},
{
"id": 2,
"exam_id": 1,
"subject_id": 2,
"student_id": 2,
"mark": 61
}
]
}
Ouptut:
{
"student_mark_details": [
{
"abc": {
"roll_number": 10,
"Prelim": [
{
"subject_name": "math",
"mark": 51
}
]
},
"pqr": {
"roll_number": 12,
"Prelim": [
{
"subject_name": "english",
"mark": 61
}
]
}
}
]
}
i tried using loops and accesing student_id in both object and comparing them but code gets too messy and complex,is there any way i can use map() or filter() in this or any other method.
i have no idea where to start,my brain is fried i know im asking lot but help will be appreciated (any link/source where i can learn this is fine too)
Your output object really has a weird format: student_mark_details is an array of size 1 that contains an object that has all your students in it. Anyway, this should give you what you need. It is a format that you find often because it is a system with primary key and secondary key used a lot in databases.
The key to manage that is to start with what is at the core of what you are looking for (here, you want to describe students, so you should start from there), and then navigate the informations you need by using the primary/secondary keys. In JS, you can use the find() function in the case where one secondary key can be linked only to one primary key (ex: one mark is linked to one exam), and the filter() function when a secondary key can be linked to multiple secondary keys (ex: a student is linked to many grades).
I am not sure if this is 100% what you need because there are maybe some rules that are not shown in your example, but it solves the problem you submitted here. You might have to test it and change it depending of those rules. I don't know what your level is so I commented a lot
const data = {
"students_detail": [
{
"student_id": 1,
"name": "abc",
"roll_number": 10
},
{
"student_id": 2,
"name": "pqr",
"roll_number": 12
}
],
"subject_details": [
{
"subject_id": 1,
"subject_name": "math"
},
{
"subject_id": 2,
"subject_name": "english"
}
],
"exam_details": [
{
"exam_id": 1,
"exam_name": "Prelim"
}
],
"mark_details": [
{
"id": 1,
"exam_id": 1,
"subject_id": 1,
"student_id": 1,
"mark": 51
},
{
"id": 2,
"exam_id": 1,
"subject_id": 2,
"student_id": 2,
"mark": 61
}
]
}
function format(data) {
const output = {
"student_mark_details": [{}]
};
//I start by looping over the students_detail because in the output we want a sumary by student
data.students_detail.forEach(student => {
//Initialization of an object for a particular student
const individualStudentOutput = {}
const studentId = student.student_id;
const studentName = student.name;
//The rollNumber is easy to get
individualStudentOutput.roll_number = student.roll_number;
//We then want to find the exams that are linked to our student. We do not have that link directly, but we know that our student is linked to some marks
//Finds all the marks that correspond to the student
const studentMarkDetails = data.mark_details.filter(mark => mark.id === studentId);
studentMarkDetails.forEach(individualMark => {
//Finds the exam that corresponds to our mark
const examDetail = data.exam_details.find(exam => individualMark.exam_id === exam.exam_id);
//Finds the subject that corresponds to our mark
const subjectDetail = data.subject_details.find(subject => individualMark.subject_id === subject.subject_id);
//We then create a grade that we will add to our exam
const grade = {
subject_name: subjectDetail.subject_name,
mark: individualMark.mark
}
//We then want to add our grade to our exam, but we don't know if our output has already have an array to represent our exam
//So in the case where it does not exist, we create one
if (!individualStudentOutput[examDetail.exam_name]) {
individualStudentOutput[examDetail.exam_name] = [];
}
//We then add our grade to the exam
individualStudentOutput[examDetail.exam_name].push(grade);
});
//Now that we have finished our individual output for a student, we add it to our object
output.student_mark_details[0][studentName] = individualStudentOutput;
})
return output;
}
console.log(JSON.stringify(format(data)))
I want to limit a query and get its total length in mongoose
like this:
comment: [1,2,3,4,5,6,7,8,9,10] //length 10
const comments = await CommentModel.find().limit(3).count() //this does not work;
console.log(comments)
output:
{ length: 10, comments: [1, 2, 3] }
thanks a lot.
You can use the project object into the query like this:
db.collection.find({},
{
"_id": 0,
"comment": {
"$slice": 3
},
"length": {
"$size": "$comment"
}
})
Example here where the output is:
[
{
"comment": [
1,
2,
3
],
"length": 10
}
]
I'm trying to extract "translations" Array "text" and "verses" array "verse_key" data from below json response using Alamofire and swift3.
{
"verses": [
{
"id": 1,
"verse_number": 1,
"chapter_id": 1,
"verse_key": "1:1",
"text_madani": "بِسْمِ اللَّهِ الرَّحْمَٰنِ الرَّحِيمِ",
"text_indopak": "بِسْمِ اللّٰهِ الرَّحْمٰنِ الرَّحِيْمِ",
"text_simple": "بسم الله الرحمن الرحيم",
"juz_number": 1,
"hizb_number": 1,
"rub_number": 1,
"sajdah": null,
"sajdah_number": null,
"page_number": 1,
"audio": {
"url": "versesAbdulBaset/Mujawwad/mp3/001001.mp3",
"duration": 6,
],
"format": "mp3"
},
"translations": [
{
"id": 102574,
"language_name": "english",
"text": "In the name of Allah, the Beneficent, the Merciful.",
"resource_name": "Shakir",
"resource_id": 21
}
],
}
],
"meta": {
"current_page": 1,
"next_page": null,
"prev_page": null,
"total_pages": 1,
"total_count": 7
}
}
I'm new to swift and I can't find a way to achieve this. How can I get the values of "translations" Array "text" and "verses" array "verse_key" ?
thanks advance
Use swiftyJSON.
switch response.result{
case .success(let data) :
let json = JSON(data)
let verses = json["verses"].Stringvalue
print(verses) //get all verses
print(verses["verse_key"].Stringvalue) // get "verse_key"
break
You can take each values from this json by giving the key names. If you want to get the "verses" , use json["verses"].You can also use JSONdecoder.
I have called a webapi and I got json data
{
"orderId": 26,
"userId": "53cf1e15",
"user": {
"editablePropertyNames": [],
"email": "rajesh#tech.com",
"firstName": "Rajesh",
"id": "53cf1e15",
"identities": [],
"lastName": "kumar",
"missingProperties": [],
"phoneNumber": "45877298"
},
"locationId": 4024,
"pickupType": 1,
"pickupTimeUtc": "2015-11-27T17:33:00.417"
},
{
"orderId": 601,
"userId": "06bf5983",
"user": {
"editablePropertyNames": [],
"email": "rtest#wa.com",
"firstName": "Rakesh",
"id": "06bf5983",
"identities": [],
"lastName": "Pkumar",
"missingProperties": [],
},
"locationId": 424,
"pickupType": 1,
"pickupTimeUtc": "2016-11-16T21:30:00",
"total": 4.32,
"tax": 0.83
}
var PickupMethodEnum = _enum({
DineIn: 1, DriveThru: 2, TakeOut: 3
})
index.html
I have 5 columns
#imageIndicator Name PickupName Total scheduledTime
car.png Kumar 1 4.32 2015-11-27T17:33:00.417
my problem is
I want to display value instead of "1" in pickupName column. ( DineIn: 1, DriveThru: 2, TakeOut: 3).
show image in #imageindicaor column if pickupName ="DriveThru" otherwise hide the image.
show scheduledTime in custom format
if scheduledTime is current date then display as 12:15 pm.
if scheduled time is tomorrow date the display as 8/10 - 7:00am.
if pickupName ="TakeOut" then change that` row background color to gray and then remove that row after 2 minutes.
I want to display value instead of "1" in pickupName column. ( DineIn: 1, DriveThru: 2, TakeOut: 3).
Object.keys( objectName )[ propertyIndex ]
will return the desired property's name
The rest of your issues can be resolved with conditional statements once you've obtained the JSON data. You haven't provided your attempt so there isn't much to work with.
Hi for first point you need to write your enum properly numbers:"String" because you are getting numbers from JSON.
//Global Object
var pickupNameEnum = {
0: "DineIn",
1: "DriveThru",
2: "TakeOut"
};
Write a function as showRow(singleRowObject) in which while traversing your JSON
function showRow(singleRowObject){
var imageString="";
var hideImage=false;
var showString='';
var retutnObject={};
if(pickupNameEnum[singleRowObject.pickupType]!=undefiend){
showString='DineIn';
//DineIn
}else if(singleRowObject.pickupType==){
//DriveThru
showString='DriveThru';
imageString="<img src='abc.png' alt='img'></img>";
}else if(singleRowObject.pickupType==){
//TakeOut and change Color on basis of this flag
hideImage=true;
showString='TakeOut ';
}
retutnObject.hideImage=hideImage;
retutnObject.imageString=imageString;
retutnObject.showString=showString;
}
For date split dateString and refer to this question
For Removing Row change refer this
I'm trying to create a JSON array to send it to my web service. This is how my json should look like:
[{
"tipus": 1,
"proveidor": 3,
"atributs": {
"atribut":{
"id": 1,
"valor": 8
},
"atribut":{
"id": 2,
"valor": 500
}
}
}]
So, I have two general values "tipus" and "proveidor" and multiple "atributs" each "atribut" is composed with "id" and "valor".
When I construct the json I get this instead of what I want:
[
2:{
"tipus": 1,
"proveidor": 3,
1:{
"id": 1,
"valor": 8
},
0:{
"id": 2,
"valor": 500
}
}]
This is how I'm building the json:
// For every founded in $scope.atrb i need to create an 'atribut' element into my json
$scope.a = [];
var key;
for(key in $scope.atrb){
var newField = {
"idatributs_actiu": $scope.atrb[key].idatributs_actiu,
"nomAtribut": $scope.atrb[key].nomAtribut,
"valor": $scope.atrb[key].valor,
"idActiu": $routeParams.idTipusActiu,
"value": "",
"ordre": $scope.atrb[key].ordre,
"idatributs_generics": $scope.atrb[key].idatributs_generics
};
$scope.a.push(newField);
}
$scope.f = $scope.a;
});
var generics = {
"nom": $scope.nom,
"tipus": $routeParams.idTipusActiu,
"proveidor": $scope.proveidor.id
};
$scope.a.push(generics);
It's my first project with angular and I'm not sure if I'm building the json appropriately, basically i use an array to build a json but I don't know how to nested it 'atribut' inside 'atributs'.
The main idea is to read the 'generics' atributes and then loop through 'atributs' and read all 'atribut' element getting the properties.
Regards
Like S4beR and Kevin B told me, I just need to do an JS array. This is in my controller:
var obj = { generics: g, atributs: $scope.a };
g: it's an object with the generic properties
$scope.a: this is an array with 'atribut' objects which contais all
the properties I need save to.