Searching a .json file and displaying with Discord.js - json

What I am trying to is:
User does !check (id)
The bot will search a json file
[
{
"name": “adam”,
"age": “16”,
"id": "9"
},
{
"name": “jack”,
"age": “18”,
"id": "10"
}
]
Example:
!check 9
The bot will then reply with
name: adam
age:16
id:9
How can ı do that?

You can first import the JSON file by using require, filter through them to find out the entry having the specific ID you want and then respond to the interaction. A simplified version would look something like this:
// For demo purposes, I have added the JSON object directly in the code.
// But in your code, you can just do something like this:
// const entries = require("./filepath/to/json/file")
const entries = [{
"name": "adam",
"age": "16",
"id": 9
},
{
"name": "jack",
"age": "18",
"id": 10
}
]
const objId = 9
const filteredObj = entries.filter((obj) => obj.id === objId)[0]
const name = filteredObj.name
const age = filteredObj.age
const id = filteredObj.id
console.log("Name: ", name)
console.log("Age: ", age)
console.log("Id: ", id)

Related

Access json data based on dynamic route nextjs

I have a json file that contains content for several different pages that are under a "service" category. I use dynamic routes in nextJS by having a file as "[serviceId].tsx", this routing works. However I have a json file where I want to use the [serviceId] provided in the route to access information.
I have the following code in my [serviceId].tsx file:
const json = jsonFile.services
const router = useRouter()
const serviceId = router.query.serviceId
return (
<div>
<ArticleWithPicture title={content.title} description={content.description}/>
</div>
)
}
My json file looks similar to this (ive edited it to be more clear for this example):
{
"serviceId":
[
{
"service1": {
"id": "xx",
"title": "xxx",
"description": "xx",
"featuredCompany":
[
{ "id": "1",
"name": "xxx",
"companyPageURL": "/",
"imagePath": "xxx",
"description": "xxx",
"additionalServices": {
"service1": "xxx",
"service2": "xxx"
},
"instagramURL":"/",
"twitterURL": "/"
}
]
}
},
{
"service2": {
"id": "xxx",
"title": "xxx",
"description": "xxx",
"featuredCompany":
[
{ "id": "1",
"name": "xxx",
"companyPageURL": "/",
"imagePath": "xxx",
"description": "xxx",
"additionalServices": {
"service1": "xxx",
"service2": "xx"
},
"instagramURL":"/",
"twitterURL": "/"
}
]
}
}
]
}
Basically, each Service has the content for each indiviual page. So I want to dynamically set for instance the title of my component "ArticleWithPicture" based on the corresponding title in my json file based on the serviceId that I get from router.query.serviceId. However when I try the following code:
<ArticleWithPicture title={json.{serviceId}.title}/>
I get error (this is due to how I use "{}" within a "{}", is there a way to do this better?
But I also cannot access it if I do eg:
const title = json.serviceId.title
or (what is what I actually want to do ie: query the json file based on my serviceId provided by "router.query.serviceId")
const title = json.{serviceId}.title
I guess something might be wrong with either my json file structure or how I try to access it. Any advice would be appreciated.
Thanks!
I'm assuming the JSON you provided is your entire jsonFile.
If the JSON you provided is just jsonFile.services, then change any uses of jsonFile to jsonFile.services
and update the type.
The format of the JSON isn't great for your use case because there's a lot of unnecessary wrapping.
With your current JSON
Assuming you cannot modify the format of the JSON, you would have to find the service from the serviceId array:
function getService(json, serviceId) {
return json.serviceId
.find((serviceWrapper) => serviceWrapper[serviceId] !== undefined)
?.service;
}
A fully typed example:
type Service = {
id: string
title: string
description: string
// ...
};
// you don't have to use this, I just included it for clarity
type JsonFile = {
serviceId: {
[serviceId: string]: Service
}[]
};
function getService(json: JsonFile, serviceId: string): Service | undefined {
return json.serviceId
.find((serviceWrapper) => serviceWrapper[serviceId] !== undefined)
?.service;
}
// declare const jsonFile: JsonFile;
export default function ServicePage() {
const router = useRouter();
const serviceId = router.query.serviceId as string;
const content = getService(jsonFile, serviceId);
if (!content) return (
<div>
{'Article doesn\'t exist.'}
</div>
);
return (
<div>
<ArticleWithPicture title={content.title} description={content.description} />
</div>
);
}
With better JSON
An example JSON that would need less unwrapping is:
{
"service1": {
"id": "xx",
"title": "xxx",
// ...
},
"service2": {
"id": "xxx",
"title": "xxx",
// ...
}
}
type JsonFile = {
[serviceId: string]: Service
}
Then you would be able to just do jsonFile[serviceId] or jsonFile.services[serviceId] to get a service.

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"
}
]

Add JSON data fields names Angular

I have data with no field names, I would like to append to each row a field name
[
"James Vega",
"23",
"abc#test.com"
],
I want to add the fields to this JSON data, I'm working on Angular 6
[
{ "name": "James Vega" },
{ "Age": 23 },
{ "email": "abc#test.com" }
],
You just use map function to transform the object you want
let arr=
[
[
"James Vega",
"23",
"abc#test.com"
]
];
let arr_transform=arr.map(el=> ({
name:el[0],
age:el[1],
email:el[2]
}));
console.log(arr_transform)
If your order of property would be the same, then it is possible to create a mapping and map it with O(1):
const foo = [
"James Vega",
"23",
"abc#test.com"
];
const mapping = {0: 'name', 1: 'Age', 2: 'email'};
const result = foo.map((el, i) => ({[mapping[i]]: el}));
console.log(result);

How access the access the whole object by its id

Here we are having two JSON called 1.contacts and 2.workers contacts json is having id called serviceId is nothing but id of workers. when i try to display contacts i want to display workers relevant to that contacts. Here is the stackblits DEMO
Here i have updated stackblitz using sample your data as Array.
https://stackblitz.com/edit/angular-movie-read-load-json-sample-eg-ujzzx1
Code:-
let finalResult:any[]=[];
for(let contact of this.contacts){
if(contact.serviceId){
finalResult.push(this.workers.filter(o=>o.id == contact.serviceId));
}
}
console.log("finalResult",finalResult);
You can gather the IDs from the contacts IDs in a map by using map then reduce. After that you iterate over your workers and check in the previously generated map if their serviceId is one of the map's keys.
It looks like this
const contacts = [{
"name": "Jhon Doe",
"gender": "Male",
"serviceId": "e39f9302-77b3-4c52-a858-adb67651ce86",
},
{
"name": "Peter Parker",
"gender": "Male",
"serviceId": "e39f9302-77b3-4c52-a858-adb67651ce86",
},
{
"name": "Mark Wood",
"gender": "Male",
"serviceId": "38688c41-8fda-41d7-b0f5-c37dce3f5374",
},
{
"name": "Mary Jane",
"gender": "Female",
"serviceId": "38688c41-8fda-41d7-b0f5-c37dce3f5374",
}
];
const workers = [
{
"id": "e39f9302-77b3-4c52-a858-adb67651ce86",
"name": "Alfy Odhams"
},
{
"id": "38688c41-8fda-41d7-b0f5-c37dce3f5374",
"name": "Allsun Suttle"
},
{
"id": "ed780d15-428b-4bcd-8a91-bacae8b0b72e",
"name": "Alvinia Ettritch"
},
{
"id": "40665c50-ff74-4e81-b968-e127bdf1fe28",
"name": "Ambrosi Lindenstrauss"
}
];
const contactsIDs = contacts.map(c => c.serviceId).reduce((acc, curr) => {
acc[curr] = true;
return acc;
}, {});
const filteredWorkers = workers.filter(w => w.id in contactsIDs);
console.log(filteredWorkers);

How to Check a value in a nested JSON using Postman

I have a nested JSON returned from an API that I am hitting using a GET request, in POSTMAN chrome app. My JSON looks like this.
{
"resultset": {
"violations": {
"hpd": [
{
"0": {
"ViolationID": "110971",
"BuildingID": "775548",
"RegistrationID": "500590",
"Boro": "STATEN ISLAND",
"HouseNumber": "275",
"LowHouseNumber": "275",
"HighHouseNumber": "275",
"StreetName": "RICHMOND AVENUE",
"StreetCode": "44750",
"Zip": "10302",
"Apartment": "",
"Story": "All Stories ",
"Block": "1036",
"Lot": "1",
"Class": "A",
"InspectionDate": "1997-04-11",
"OriginalCertifyByDate": "1997-08-15",
"OriginalCorrectByDate": "1997-08-08",
"NewCertifyByDate": "",
"NewCorrectByDate": "",
"CertifiedDate": "",
"OrderNumber": "772",
"NOVID": "3370",
"NOVDescription": "§ 27-2098 ADM CODE FILE WITH THIS DEPARTMENT A REGISTRATION STATEMENT FOR BUILDING. ",
"NOVIssuedDate": "1997-04-22",
"CurrentStatus": "VIOLATION CLOSED",
"CurrentStatusDate": "2015-03-10"
},
"count": "1"
}
]
}
},
"count": "1",
"total_page": 1,
"current_page": 1,
"limit": [
"0",
"1000"
],
"status": "success",
"error_code": "",
"message": ""
}
I am trying to test whether my response body has "ViolationID":"110971".
I tried the below code in postman:
var jsonData =JSON.parse(responseBody);
tests["Getting Violation Id"] = jsonData.resultset.violations.hpd[0].ViolationID === 110971;
Two issues I noticed in the provided data. The following suggestions might help you:
Add missing closing braces at the end.
Add missing 0 in the index like this: resultset.violations.hpd[0].0.ViolationID
If the hpd array always contains only 1 member, the test might be pretty straightforward:
pm.test('Body contains ViolationID', () => {
const jsonBody = pm.response.json();
const violationId = jsonBody.resultset.violations.hpd[0]["0"].ViolationID;
pm.expect(parseInt(violationId)).to.eql(110971);
})
However, if hpd array might contain more than one member, it gets a bit trickier. I would suggest mapping only ViolationID keys from nested objects:
pm.test('Body contains ViolationID', () => {
const jsonBody = pm.response.json();
const violationIds = jsonBody.resultset.violations.hpd.map(hpd => hpd["0"].ViolationID);
pm.expect(violationIds).to.contain('110971');
})