Okay, I'm a bit new to JSON in Discord.js Bot Development, And I'm currently making a command where it grabs all of the data in a json file and splits it so it looks nicely formatted.
Currently have:
let Games = {
"1": "Jailbreak",
"2": "Adopt Me",
"3": "Bubble Gum Simulator",
"4": "Thick Legends",
"5": "Arsenal",
"6": "Legends Of Speed",
"7": "Speed Champions",
"8": "Build A Boat For Treasure",
"9": "Boxing Simulator",
"10": "Flight Simulator",
"11": "Mad City",
"12": "Redwood Prison",
"13": "Horrific Housing",
"14": "Welcome To Bloxburg",
"15": "Tower Of Hell"
}
function getGames(lol) {
lol = JSON.parse(Games[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15]);
for (let j in lol) {
return "• " + lol[j];
}
}
I want to group all of the Games and make it output:
"• example\n"
Any answers?
You can get all object values, use map to add • and join it with '\n'.
Like this:
let Games = {
"1": "Jailbreak",
"2": "Adopt Me",
"3": "Bubble Gum Simulator",
"4": "Thick Legends",
"5": "Arsenal",
"6": "Legends Of Speed",
"7": "Speed Champions",
"8": "Build A Boat For Treasure",
"9": "Boxing Simulator",
"10": "Flight Simulator",
"11": "Mad City",
"12": "Redwood Prison",
"13": "Horrific Housing",
"14": "Welcome To Bloxburg",
"15": "Tower Of Hell"
}
console.log(getGames(Games))
function getGames(gameList) {
return Object.values(gameList).map(game => `• ${game}`).join('\n')
}
Live example
let Games = {
"1": "Jailbreak",
"2": "Adopt Me",
"3": "Bubble Gum Simulator",
"4": "Thick Legends",
"5": "Arsenal",
"6": "Legends Of Speed",
"7": "Speed Champions",
"8": "Build A Boat For Treasure",
"9": "Boxing Simulator",
"10": "Flight Simulator",
"11": "Mad City",
"12": "Redwood Prison",
"13": "Horrific Housing",
"14": "Welcome To Bloxburg",
"15": "Tower Of Hell"
}
console.log(getGames(Games))
function getGames(gameList) {
return Object.values(gameList).map(game => `• ${game}`).join('\n')
}
You can get an array of the object values with Object.values()
let gamenames = Object.values(games)
Then,you can loop through the array elements to add them to a string.
let myString = "List: \n"
gamenames.forEach((val) => {
myString += `• ${val} \n`
})
myString is now equal to an organized list of the games! It should look like:
List:
• Jailbreak
• Adopt me
...etc..
(The list does put every single value on a seperate line,but StackOverflow doesn't want to show them properly for some reason)
Hope this helped! If it did,please mark my question as a valid answer.
Related
Can we change the sequence of json items?
For example:
[
{
"category": "Science: Mathematics",
"type": "multiple",
"difficulty": "medium",
"question": "In a complete graph G, which has 12 vertices, how many edges are there?",
"correct_answer": "66",
"incorrect_answers1": "67",
"incorrect_answers2 : "34",
"incorrect_answers3 : "11"
},
{
"category": "Science: Mathematics",
"type": "multiple",
"difficulty": "medium",
"question": "In base 2, what is 1 + 1?",
"incorrect_answers1": "2",
"incorrect_answers2 : "01",
"correct_answer": "10",
"incorrect_answers3 : "11"
},
{
"category": "Science: Mathematics",
"type": "multiple",
"difficulty": "medium",
"question": "In the hexadecimal system, what number comes after 9?",
"incorrect_answers1": "10",
"incorrect_answers2 : "The Number 0",
"correct_answer": "The Letter A",
"incorrect_answers3 : "16"
}
]
As mentioned in the comments that re-ordering JSON data is impossible and also not required.
For the current situation, you have to loop across the parent array containing the JSON objects, create a local array variable to get the list of re-ordered answers, push all the answers to this array and shuffle it using a library like lodash (https://lodash.com/docs/#shuffle) or a custom random functions, whatever works for your needs.
You can place this array within each object of this JSON while looping and give it a meaningful key like shuffled_answers.
So now your item structure will look like this:
{
"category": "Science: Mathematics",
"type": "multiple",
"difficulty": "medium",
"question": "In base 2, what is 1 + 1?",
"incorrect_answers1": "2",
"incorrect_answers2" : "01",
"correct_answer": "10",
"incorrect_answers3" : "11",
"shuffled_answers": ["2", "11", "10", "11"]
}
You can then use this array to display answer choices in your UI to ask user the question and use the correct_answer key to compare the correct answer from the user's choice.
I'm linking here a video tutorial for a very similar App developed in Vue using the above logic. You can refer for more insight about apps like these and use it for your requirements.
Hope that helps.
I am working on a food delivery app, which uses parse as its backend. I am facing a problem while calling the placeOrder API through
PFCloud.callFunction(inBackground: PlaceOrder, withParameters: params) { (data, err) in}
Please have a look at the JSON which I need to post below.
{
"source": "card_1EVYuOEynlyM6L4SHgBMJYRQ",
"userId": "YjSZYSXEp7",
"data": {
"menuItems": [{
"id": "QSYa2JDcIm",
"title": "Rice With Tibss(Beef)",
"menuTitle": "Rice With Tibss",
"submenuItem": [{
"id": "zaOo6G4KSV",
"name": "Beef",
"price": 12,
"desc": "Fillings?"
}],
"price": 24,
"qty": 1,
"storeId": "yqBCDmzaDP",
"storeName": "Ibex Ethiopian Cusine and Bar",
"orderType": "takeout",
"taxState": 0.0925,
"storeInfo": {
"cart_storeId": "yqBCDmzaDP",
"cart_storeName": "Ibex Ethiopian Cusine and Bar",
"cart_storeImage": "https://res.cloudinary.com/http-get-tolofood-com/image/upload/c_scale,h_199,q_auto,w_270/v1461575640/Ibex_lopx38.jpg",
"cart_storeCuisine": "Ethiopian",
"cart_storeDescription": "We always serve a quality food. We always serve a quality food. We always serve a quality food. We always serve a quality food.",
"cart_storeRating": 3.33,
"cart_storeDelivery": false,
"takeout": true,
"address": "12255 Greenville Ave,Dallas, TX 75243",
"slugname": "TX_DAL_ibex_ethiopian_cuisine_and_bar",
"multiple_location": false,
"cart_storeDeliveryFee": 15,
"cart_storeServes": "Lunch,Dinner",
"busy": false,
"cart_storeSeoSlug": "ibex-ethiopian-cusine-and-bar"
},
"enable": true,
"voice_read_mi_label": "fbgcb",
"voice_read_mi_option": false,
"menuTypeName": "Standard"
}],
"lastOrderType": "takeout",
"searchedAddress": "takeout",
"timeData": {
"day": "06-05-2019",
"time": "12:55 am",
"tz": "America/Los_Angeles"
}
},
"unavailable_option": "restaurant_recommendation"
}
And below is the Swift code which I have used to make pass it.
let storeInfo: Dictionary = [CartStoreId: self.cartStoreId, CartStoreName: self.cartRestaurantName, CartStoreImage: self.cartStoreImage, CartStoreCuisine: self.cartStoreCuisine, CartStoreDescription: self.cartStoreDescription, CartStoreRating: self.cartStoreRating, CartStoreDelivery: self.cartStoreDelivery, Takeout: self.takeOut, Address: self.address, Slugname: self.slugName, MultipleLocation: self.multipleLocation, CartStoreDeliveryFee: self.cartStoreDelivery, CartStoreServes: self.cartStoreServes, Busy: self.busy, CartStoreSeoSlug: self.cartStoreSeoSlug] as Dictionary
let subMenuItem = ["id": "zaOo6G4KSV", "name": "Beef", "price": 12, "desc": "Fillings?", "voice_read_submi_label":"bf", "voice_read_submi_option":false, "disabled": false] as [String: Any]
let ordersDictionary = [
"id" : "1234",
"title" : "Test",
"menuTitle" : "MenuName",
"price" : 23,
"qty" : 2,
"storeId" : 23,
"orderType" : "standard",
"taxState" : 0.22,
"enable" : true,
"menuTypeName" : "Type Name",
"voice_read_mi_label":"fdfs",
"voice_read_mi_option":"false",
"submenuitem": subMenuItem,
"storeInfo": storeInfo
] as Dictionary
let timeData = ["day" : 17-06-2019, "time": "11:00 AM", "tz": "America/Los_Angeles"] as Dictionary
let data = ["menuItems": ordersDictionary, "lastOrderType": "takeout", "searchedAddress": "takeout", "timeData" : timeData] as Dictionary
let params = [UserId: self.userId, "source":"card_1EVYuOEynlyM6L4SHgBMJYRQ", "data": data, "unavailable_option":"restaurant_recommendation","_ApplicationId":"6EuadToYoFGJhI1sX8XnuFBz9tp9l3yH6HxzzXZO", "_JavaScriptKey":"rQkALu9saFtF2oq9yCibyw6mEcs3PVqct3uuP6vg", "_ClientVersion":"js1.6.14", "_InstallationId":"444ec64d-5fcc-7b8e-596e-6be627892c2a",
"_SessionToken":"r:c966376120c8eca77aa63c29d5bebe1a"] as Dictionary
After all this is done I call the parse function like below.
PFCloud.callFunction(inBackground: PlaceOrder, withParameters: params) { (data, err) in
if err != nil {
print(err!)
} else {
print(data!)
}
}
But this gives me error after a few seconds saying
"Error Domain=NSCocoaErrorDomain Code=3840 "JSON text did not start with array or object and option to allow fragments not set." UserInfo={NSDebugDescription=JSON text did not start with array or object and option to allow fragments not set.}"
I have searched the web with the error and made fixes accordingly but still no success. Please help me guys.
I noticed that your params var is not compatible with the JSON you sent, there are more fields and also missing fields. Moreover, menuItems and submenuItem are an Array in your JSON and an Object in your code. It is probably making the cloud code function to fail and you are therefore not receiving back a valid JSON. Try the following and check if it works. In the case it works, just replace the values by your vars.
let params = [
"source": "card_1EVYuOEynlyM6L4SHgBMJYRQ",
"userId": "YjSZYSXEp7",
"data": [
"menuItems": [[
"id": "QSYa2JDcIm",
"title": "Rice With Tibss(Beef)",
"menuTitle": "Rice With Tibss",
"submenuItem": [[
"id": "zaOo6G4KSV",
"name": "Beef",
"price": 12,
"desc": "Fillings?"
]],
"price": 24,
"qty": 1,
"storeId": "yqBCDmzaDP",
"storeName": "Ibex Ethiopian Cusine and Bar",
"orderType": "takeout",
"taxState": 0.0925,
"storeInfo": [
"cart_storeId": "yqBCDmzaDP",
"cart_storeName": "Ibex Ethiopian Cusine and Bar",
"cart_storeImage": "https://res.cloudinary.com/http-get-tolofood-com/image/upload/c_scale,h_199,q_auto,w_270/v1461575640/Ibex_lopx38.jpg",
"cart_storeCuisine": "Ethiopian",
"cart_storeDescription": "We always serve a quality food. We always serve a quality food. We always serve a quality food. We always serve a quality food.",
"cart_storeRating": 3.33,
"cart_storeDelivery": false,
"takeout": true,
"address": "12255 Greenville Ave,Dallas, TX 75243",
"slugname": "TX_DAL_ibex_ethiopian_cuisine_and_bar",
"multiple_location": false,
"cart_storeDeliveryFee": 15,
"cart_storeServes": "Lunch,Dinner",
"busy": false,
"cart_storeSeoSlug": "ibex-ethiopian-cusine-and-bar"
],
"enable": true,
"voice_read_mi_label": "fbgcb",
"voice_read_mi_option": false,
"menuTypeName": "Standard"
]],
"lastOrderType": "takeout",
"searchedAddress": "takeout",
"timeData": [
"day": "06-05-2019",
"time": "12:55 am",
"tz": "America/Los_Angeles"
]
],
"unavailable_option": "restaurant_recommendation"
]
I have to create a web-proxy script for my angularjs files because I got the error of CORS(Cross Origin Request Method) and I dont have any options to use Access Control Allow Origin because I cant make any changes to my server end.
My backend data is in java. So please someone tell me how to make a web-proxy for my angularjs application.
Or is there anyway to bypass the cors request from my browser.
A quick work around using foreach and json_decode.
If your print_r($json) comes in this format:
Array
(
[0] => Array
(
[studentid] => 5
[firstame] => jagdjasgd
[lastname] => kjdgakjd
[gender] => 1
[email] => dgahsdg#em.com
[fathername] => hashsdh
[mothername] => djhavshd
[birthday] => 2016-03-21
[address] => gafdhfadhs
[tenth] => 45.235
[twelfth] => 56.25
)
)
This will do the trick:
if ($_SERVER['REQUEST_METHOD'] == 'POST')
{
$json = json_decode(file_get_contents("php://input"), true);
//print_r($json);
$data =array();//Open blank array for student data
$num = array();//Open Blank array for number of student
foreach($json as $k => $v):
$num [] = $v; //number of student
if(is_array($v)){
foreach($v as $key=>$val):
$data[$key] = $val;//Student data
endforeach;
}
endforeach;
$row= count($num);//Put number of student in $row
for($i=1; $i<=$row; $i++){
$q = 'INSERT INTO table (`col1`)
VALUES($data['studentid'])';//Looping through sql statement
}
Hope this will help.
User json_decode with true params
$data = "{"studentid":"5","firstame":"jagdjasgd","lastname":"kjdgakjd","email":"dgahsdg#em.com"}";
$d = json_decode($data,true); // true means it will result in aaray
print_r($d);
$stdId = $d['studentid'];
$fname = $d['firstname'];
$lname = $d['lastname'];
$mail = $d['email'];
EDIT:
For multiple json data:
$data = '[
{
"0": "1",
"studentid": "1",
"1": "David",
"firstname": "David",
"2": "Beckham",
"lastname": "Beckham",
"3": "1",
"gender": "1",
"4": "david123#gmail.com",
"email": "david123#gmail.com",
"5": "Beckham",
"fathername": "Beckham",
"6": "Beckhamii",
"mothername": "Beckhamii",
"7": "2016-03-13",
"birthday": "2016-03-13",
"8": "dgasdhghasd\nkajsdgjaksdh\nkahdgjaksgdas",
"address": "dgasdhghasd\nkajsdgjaksdh\nkahdgjaksgdas",
"9": "58.25",
"tenth": "58.25",
"10": "62.25",
"twelfth": "62.25"
},
{
"0": "3",
"studentid": "3",
"1": "Chris",
"firstname": "Chris",
"2": "Gayle",
"lastname": "Gayle",
"3": "1",
"gender": "1",
"4": "chrisgayle#email.com",
"email": "chrisgayle#email.com",
"5": "Chris Potters",
"fathername": "Chris Potters",
"6": "Christine",
"mothername": "Christine",
"7": "2016-04-20",
"birthday": "2016-04-20",
"8": "adhafsdh\njgadahksgdkjas\njagdjahsdlkajsld\nkajsgdjlahsdlkas",
"address": "adhafsdh\njgadahksgdkjas\njagdjahsdlkajsld\nkajsgdjlahsdlkas",
"9": "87.587",
"tenth": "87.587",
"10": "98.256",
"twelfth": "98.256"
},
{
"0": "5",
"studentid": "5",
"1": "jagdjasgd",
"firstname": "jagdjasgd",
"2": "kjdgakjd",
"lastname": "kjdgakjd",
"3": "1",
"gender": "1",
"4": "dgahsdg#em.com",
"email": "dgahsdg#em.com",
"5": "hashsdh",
"fathername": "hashsdh",
"6": "djhavshd",
"mothername": "djhavshd",
"7": "2016-03-21",
"birthday": "2016-03-21",
"8": "gafdhfadhs\nagdkjashdas\ndjkahsdklsaj",
"address": "gafdhfadhs\nagdkjashdas\ndjkahsdklsaj",
"9": "45.235",
"tenth": "45.235",
"10": "56.25",
"twelfth": "56.25"
}
]';
$json = json_decode($data, true);
echo '<pre>';
foreach ($json as $key => $value) {
echo "StudentID: ".$value['studentid']."<br>";
}
Output:
StudentID: 1
StudentID: 3
StudentID: 5
Decode ur array like below..
$newarr= json_decode('urjsonstring');
extract($newarr);
$query="insert into stud values($studentid, $firstname,$lastname...)";
I have a json data which looks like this:
{
"id": 355,
"title": "ZISIMOPOULOS LTD",
"cat": "Contractor - High Pressure, Cutting & Breaking, Hydrodemolition, Surface Preparation - UHP, Tube, Pipe & Bundle Cleaning",
"catids": {
"1": 17,
"2": 18,
"3": 21,
"4": 26,
"5": 27
},
"link": "http://wja.dev/members/zisimopoulos-ltd/",
"memberType": "C1 - Water Jetting Contractor",
"email": "info#zisimopoulos.gr",
"telephone": "302104412004",
"fax": "302104416524",
"website": "www.zisimopoulos.gr",
"instructor": false
}
Each member has catids associated to it.
Now i need the filteration function, where on clicking on the categories in the left will list the member associated to that categories.
Filteration page layout
Thanks in advance.
I have Documents they have this structure:
{id: ####,
rev: ####,
"Cam_name": "Camera SX",
"colour": "white",
"manufacturer": "Sony",
"rec_limit": 180,
"Customer": ["Mike","Ann","James"]
}
{id: ####,
rev: ####,
"Cam_name": "PXSV CAM",
"colour": "white",
"manufacturer": "LG",
"rec_limit": 144,
"Customer": ["Mike","Oliver","Mr. Rain"]
}
{id: ####,
rev: ####,
"Cam_name": "LxSV Double",
"colour": "white",
"manufacturer": "Phillips",
"rec_limit": 160,
"Customer": ["Mike"]
}
And i want to make an MAP Function query where i can see ALL Cam_Names which the Customer Mike is using.
i have a simillar Map Function but this shows only the Cam_Name LxSV Double and only the Customer Mike. i want to show all Cam_Names which mike is using.
MyQuery:
function(doc){
if(doc.Customer == "Mike"){
emit(doc.Cam_name, doc.Customer)
This query gives me not the right result.
If your query looks exactly like that, then you have a syntax error. But also, doc.Customer is an array, so you can't do a simple equality check.
But checking the existence of a value in an array is totally unnecessary, your map function can simply look like this:
function (doc) {
doc.Customer.forEach(function (customer) {
emit(customer, doc.Cam_name);
});
}
Then, query your view with /{db}/_design/{ddoc}/_view/{view}?key="Mike"
Your output will look like:
{
"total_rows": 3,
"offset": 0,
"rows": [
{
"id": "####",
"key": "Mike",
"value": "Camera SX"
},
{
"id": "####",
"key": "Mike",
"value": "PXSV CAM"
},
{
"id": "####",
"key": "Mike",
"value": "LxSV Double"
}
]
}
Now, you can use this same view to find any customer, not just whomever you specify in your map function.