Checking a value in a nested JSON using Postman - javascript

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
"result": [
{
"_id": "some_id",
"name": "India",
"code": "IN",
"link": "http://www.india.info/",
"closingTime": "2017-02-25T01:12:17.860Z",
"openingTime": "2017-02-25T06:12:17.205Z",
"image": "image_link",
"status": "online",
"serverStatus": "online",
"games": [
{
"_id": "some_game_id1",
"name": "Cricket"
},
{
"_id": "some_another_id1",
"name": "Baseball"
},
{
"_id": "some_another_id_2",
"name": "Basketball"
}
]
},
{
"_id": "some_id",
"name": "Australia",
"code": "AUS",
"link": "https://www.lonelyplanet.com/aus/adelaide",
"closingTime": "2017-02-28T05:13:38.022Z",
"openingTime": "2017-02-28T05:13:38.682Z",
"image": "some_image_url",
"status": "offline",
"serverStatus": "online",
"games": [
{
"_id": "some_game_id_2",
"name": "Cricket"
},
{
"_id": "some_another_id_3",
"name": "Kho-Kho"
},
{
"_id": "some_another_id_4",
"name": "Badminton"
},
{
"_id": "some_another_id_5",
"name": "Tennis"
}
]
},
I am trying to test whether my response body has "name":"India" and the "game" with "some_game_id1" contains the "name":"cricket".
I went through this link where the answer is to have an array for "name"created and then check within the array whether the array contains the value. I tried this but my code fails.
Also, I tried searching the element by the index within the JSON body using this -
var searchJSON = JSON.parse(responseBody);
tests["name contains India"] = searchJSON.result.name[0]==="India";
But this also fails. I tried using the .value appended with the second line of above code, but it also fails. How can I check this thing?

You need to put [0] after result (which is an array) rather than name (which is a string).
Also, use a regular expression to check whether the name contains 'India', because using === only checks if the name is exactly India.
var searchJSON = JSON.parse(responseBody)
tests["name contains India"] = /India/.test(searchJSON.result[0].name)
Demo Snippet:
var responseBody = `{
"result": [{
"_id": "some_id",
"name": "India",
"code": "IN",
"link": "http://www.india.info/",
"closingTime": "2017-02-25T01:12:17.860Z",
"openingTime": "2017-02-25T06:12:17.205Z",
"image": "image_link",
"status": "online",
"serverStatus": "online",
"games": [{
"_id": "some_game_id1",
"name": "Cricket"
},
{
"_id": "some_another_id1",
"name": "Baseball"
},
{
"_id": "some_another_id_2",
"name": "Basketball"
}
]
},
{
"_id": "some_id",
"name": "Australia",
"code": "AUS",
"link": "https://www.lonelyplanet.com/aus/adelaide",
"closingTime": "2017-02-28T05:13:38.022Z",
"openingTime": "2017-02-28T05:13:38.682Z",
"image": "some_image_url",
"status": "offline",
"serverStatus": "online",
"games": [{
"_id": "some_game_id_2",
"name": "Cricket"
},
{
"_id": "some_another_id_3",
"name": "Kho-Kho"
},
{
"_id": "some_another_id_4",
"name": "Badminton"
},
{
"_id": "some_another_id_5",
"name": "Tennis"
}
]
}
]
}`
var tests = {}
var searchJSON = JSON.parse(responseBody)
tests["name contains India"] = /India/.test(searchJSON.result[0].name)
console.log(tests) //=> { "name contains India": true }

Related

Creating new json by taking url addresses from existing json and split it up Javascript

I have a json file.
[
{
"line": 1,
"elements": [
{
"start_timestamp": "2022-10-17T20:07:41.706Z",
"steps": [
{
"result": {
"duration": 12216552000,
"status": "passed"
},
"line": 5,
"name": "m0e",
"match": {
"location": "seleniumgluecode.book.user_is_on_homepagee()"
},
"keyword": "Given "
},
{
"result": {
"duration": 2074982200,
"status": "passed"
},
"line": 6,
"name": "m1e1",
"match": {
"location": "seleniumgluecode.book.user_enters_Usernamee()"
},
"keyword": "When "
}
],
"tags": [
{
"name": "#Smokee"
}
]
},
{
"start_timestamp": "2022-10-17T20:08:12.284Z",
"steps": [
{
"result": {
"duration": 12090584100,
"status": "passed"
},
"line": 12,
"name": "m0e2",
"match": {
"location": "seleniumgluecode.book2.user_is_on_homepageee()"
},
"keyword": "Given "
}
],
"tags": [
{
"name": "#Smokee"
}
]
}
],
"name": "Login Featuree",
"description": " Verify if user is able to Login in to the sitee",
"id": "login-featuree",
"keyword": "Feature",
"uri": "file:src/test/java/features/tribe/squad1/kitab.feature",
"tags": []
},
{
"line": 1,
"elements": [
{
"start_timestamp": "2022-10-17T20:08:34.480Z",
"steps": [
{
"result": {
"duration": 11366098500,
"status": "passed"
},
"line": 5,
"name": "m0e",
"match": {
"location": "seleniumgluecode.book.user_is_on_homepagee()"
},
"keyword": "Given "
}
],
"tags": [
{
"name": "#Smokee"
}
]
}
],
"name": "Login Featureefghfgh",
"description": " Verify if user is able to Login in to the sitee",
"id": "login-featureefghfgh",
"keyword": "Feature",
"uri": "file:src/test/java/features/tribe1/squad2/kitab2.feature",
"tags": []
},
{
"line": 19,
"elements": [
{
"start_timestamp": "2022-10-17T20:09:40.836Z",
"steps": [
{
"result": {
"duration": 12761711100,
"status": "passed"
},
"line": 23,
"name": "m0e",
"match": {
"location": "seleniumgluecode.book.user_is_on_homepagee()"
},
"keyword": "Given "
}
],
"tags": [
{
"name": "#Smokee"
}
]
}
],
"name": "X Feature",
"description": " Verify if user is able to Login in to the sitee",
"id": "login-featuree",
"keyword": "Feature",
"uri": "file:src/test/java/features/tribe2/test.feature",
"tags": []
}
]
I am getting url addresses in this array
document.addEventListener("DOMContentLoaded", () => {
var i = report.length;
var array = [];
for(x = 0; x < i; x++){
array.push(report[x].uri.split("/"));
}
console.log(array2);
});
This return me :
0:
(7) ['file:src', 'test', 'java', 'features', 'tribe1', 'squad1', 'kitab.feature']
1:
(7) ['file:src', 'test', 'java', 'features', 'tribe1', 'squad2', 'kitab2.feature']
2:
(6) ['file:src', 'test', 'java', 'features', 'tribe2, kitab3.feature']
I don't need file:src, test, java, features. Deleting them in 3 arrays and getting a unique array like this:
0:
(3) ['tribe1', 'squad1', 'kitab.feature']
1:
(3) ['tribe1', 'squad2', 'kitab2.feature']
2:
(2) ['tribe2, kitab3.feature']
Finally, if there are 2 elements before the .feature, I need to create a new array by considering 1 as squad and 2 as tribe. Like this:
Diagram
[tribe1
squad1
elem
1
2
name
url
squad2
elem
1
2
name
url
tribe2
elem
1
2
name
url
]
How can I do that?. Thank you.
You should try destructing the array. An example is shown below:
[a,b,c,d, ...rest] = ['file:src', 'test', 'java', 'features', 'tribe1', 'squad1', 'kitab.feature']
console.log(rest);
You can transform or create a new array based on input array with this simple logic with the help of Array.map() along with String.split() and Array.splice() method.
Live Demo :
const arr = [
{
"line": 1,
"uri": "file:src/test/java/features/tribe/squad1/kitab.feature"
},
{
"line": 1,
"uri": "file:src/test/java/features/tribe1/squad2/kitab2.feature"
},
{
"line": 19,
"uri": "file:src/test/java/features/tribe2/test.feature"
}
];
const res = arr.map(({ uri}) => uri.split('/').splice(4));
console.log(res);

How to get common value in Object Array in JavaScript

const data = {
"games": [
{
"id": "828de9122149499183df39c6ae2dd3ab",
"developer_id": "885911",
"game_name": "Minecraft",
"first_release": "2011-18-11",
"website": "https://www.minecraft.net/en-us"
},
{
"id": "61ee6f196c58afc9c1f78831",
"developer_id": "810637",
"game_name": "Fortnite",
"first_release": "2017-21-07",
"website": "https://www.epicgames.com/fortnite/en-US/home"
},
],
"developers": [
{
"id": "885911",
"name": "Mojang Studios",
"country": "US",
"website": "http://www.mojang.com",
},
{
"id": "750245",
"name": "God of War",
"country": "SE",
"website": "https://sms.playstation.com",
},
] };
I have json data like this. I want to display data like if developer_id = 885911(from games array) then print id(from developers array) and if the both are same then I want to print the name.(Mojang studios) and so on like games website etc. How can I do that?
This sample code will show you the developer of each game, if it's found:
const data = {
"games": [
{
"id": "828de9122149499183df39c6ae2dd3ab",
"developer_id": "885911",
"game_name": "Minecraft",
"first_release": "2011-18-11",
"website": "https://www.minecraft.net/en-us"
},
{
"id": "61ee6f196c58afc9c1f78831",
"developer_id": "810637",
"game_name": "Fortnite",
"first_release": "2017-21-07",
"website": "https://www.epicgames.com/fortnite/en-US/home"
},
],
"developers": [
{
"id": "885911",
"name": "Mojang Studios",
"country": "US",
"website": "http://www.mojang.com",
},
{
"id": "750245",
"name": "God of War",
"country": "SE",
"website": "https://sms.playstation.com",
},
] };
const gameDevelopers = data.games.map(g => ({
game: g.game_name,
developer: data.developers.find(d => d.id === g.developer_id)?.name || "No matching developer found"
}));
console.log(gameDevelopers)
What did you exactly need? i don't understand . But you can get value Mojang Studios
console.log(data.developers[0].name)
If you need all developer id then you can use
console.log(data.developers.map(data=>{
console.log(data.id)
}))
If you need the id where name is Mojang Studios
console.log(data.developers.map(data=>{
if(data.name == "Mojang Studios"){
console.log(data.id)
}
}))

Restructuring JSON before input

Here's an example of object from the JSON output of my database:
{
"id": "http://...",
"type": "example-type",
"title": "Example title",
"container-title": "Example container title",
"page": "1-100",
"issue": "3",
"URL": "http://www.url",
"ISSN": "0123-0123",
"author": [
{
"family": "Smith",
"given": "John"
}
],
"issued": {
"date-parts": [
[
"2000"
]
]
},
"keyword": "Sample Tag"
}
I've had enormous difficulties/bugs referring to the nested fields for author and date when building a data table. What I would like to do is somehow modify/flatten this before using it in the table (using Datatables' dataSrc as described here) and then simply call the restructured data as many times as I need using the datatables API.
So what I now refer to as issued.date-parts.0.0 would be simply year. The structure would be instead:
"authors": "John Smith", "Mark Smith"
"year": "2000"
Use the map function to get the authors
Look at this code snippet
var data = { "id": "http://...", "type": "example-type", "title": "Example title", "container-title": "Example container title", "page": "1-100", "issue": "3", "URL": "http://www.url", "ISSN": "0123-0123", "author": [ { "family": "Smith", "given": "John" }, { "family": "Smith", "given": "Mark" } ], "issued": { "date-parts": [ [ "2000" ] ] }, "keyword": "Sample Tag"};
var result = {
"authors": data.author.map((d) => `${d.given} ${d.family}`),
"year": data.issued['date-parts'][0][0]
}
console.log(result);
.as-console-wrapper {
max-height: 100% !important
}

JavaScript - Loop JSON array and match string in subarray

I have JSON array with subarrays and I want to loop it and find if username of user is for example 'admin'. If so then create JSON array contains data belonging to user 'admin' (region, sport, city etc). I don't have idea how to find it in loop and then slice it. I'm sorry for stupid question but I'm a little lost.
This is JSON array with structure what I have:
[
{
"_id": "5520f52e2c0a22541541bde1",
"region": {
"_id": "551e6779d8f1afa01bd86529",
"name": "region_name"
},
"user": {
"_id": "551a938af056a7fc099879c1",
"firstName": "John",
"lastName": "Boo",
"username": "admin",
"id": "551a938af056a7fc099879c1"
},
"__v": 0,
"sport": [
{
"_id": "551e69c6d8f1afa01bd86533",
"name": "Running"
}
],
"city": "some_city",
"advert": "some_advert",
"title": "I want to run!",
"created": "2015-04-05T08:41:18.173Z"
},
{
"_id": "552010740628cab002b3a700",
"region": {
"_id": "551e67b6d8f1afa01bd8652f",
"name": "region_name"
},
"user": {
"_id": "551a938af056a7fc099879c1",
"firstName": "Bill",
"lastName": "Foo",
"username": "bill_foo",
"id": "551a938af056a7fc099879c1"
},
"__v": 0,
"sport": [
{
"_id": "551e5e01abb74a8423410b88",
"nazev": "Hockey"
}
],
"city": "some_city",
"advert": "some_advert",
"title": "some_title",
"created": "2015-04-04T16:25:24.733Z"
}
]
Edit:
the expected result of user 'admin' is then:
[
{
"_id": "5520f52e2c0a22541541bde1",
"region": {
"_id": "551e6779d8f1afa01bd86529",
"name": "region_name"
},
"user": {
"_id": "551a938af056a7fc099879c1",
"firstName": "John",
"lastName": "Boo",
"username": "admin",
"id": "551a938af056a7fc099879c1"
},
"__v": 0,
"sport": [
{
"_id": "551e69c6d8f1afa01bd86533",
"name": "Running"
}
],
"city": "some_city",
"advert": "some_advert",
"title": "I want to run!",
"created": "2015-04-05T08:41:18.173Z"
}]
Loop through the array and pull out each item with a user with a username of admin:
var result = [];
var nameToSearchFor = 'admin';
for(var index = 0; index < arr.length; index++)
{
var item = arr[index];
if(item.user.username === nameToSearchFor)
{
result.push(item);
}
}
One solution to your problem is to search for the index that resides the admin username. In your case is at the 0 index of the json array provided. So you can get the entire object by the index, like this:
var i = 0;
for(; i< json.length; i++){
if(json[i].user.username === "admin") break;
}
With that now you can get the object with the admin data. Like this:
json[i].user.firstName
Check this plunk here
EDIT
If you want just to get that slice to a new array perhaps then you can just slice that piece of the json array, now that you have the index.
var newArray = json.slice(i, i+1);
You can use an open source project like jinqJs to perform SQL like queries on arrays.
var data = [
{
"_id": "5520f52e2c0a22541541bde1",
"region": {
"_id": "551e6779d8f1afa01bd86529",
"name": "region_name"
},
"user": {
"_id": "551a938af056a7fc099879c1",
"firstName": "John",
"lastName": "Boo",
"username": "admin",
"id": "551a938af056a7fc099879c1"
},
"__v": 0,
"sport": [
{
"_id": "551e69c6d8f1afa01bd86533",
"name": "Running"
}
],
"city": "some_city",
"advert": "some_advert",
"title": "I want to run!",
"created": "2015-04-05T08:41:18.173Z"
},
{
"_id": "552010740628cab002b3a700",
"region": {
"_id": "551e67b6d8f1afa01bd8652f",
"name": "region_name"
},
"user": {
"_id": "551a938af056a7fc099879c1",
"firstName": "Bill",
"lastName": "Foo",
"username": "bill_foo",
"id": "551a938af056a7fc099879c1"
},
"__v": 0,
"sport": [
{
"_id": "551e5e01abb74a8423410b88",
"nazev": "Hockey"
}
],
"city": "some_city",
"advert": "some_advert",
"title": "some_title",
"created": "2015-04-04T16:25:24.733Z"
}
];
var result = jinqJs()
.from(data)
.where(function(row){return row.user.username==='admin';})
.select();
document.body.innerHTML = '<pre>' + JSON.stringify(result, null, 4) + '</pre><br><br>';
<script src="https://rawgit.com/fordth/jinqJs/master/jinqjs.js"></script>

Convert a model in given json format

I have a model in which values are stored in following format:--
Language-count=3
[0]
-ID="1"
-Name="French"
[1]
-ID="2"
-Name="English"
[2]
-ID="3"
-Name="Hindi"
Titles-count=2
[0]
-ID="1"
-Name="Video1"
[1]
-ID="2"
-Name="Video2"
Countries-count=2
[0]
-ID="1"
-Name="India"
[1]
-ID="2"
-Name="USA"
and I have to convert this model in given json format:-
var models = [
{
name: 'Language',
values: [
'English',
'French',
'Hindi'
]
},
{
name: 'Title',
values: [
'Title 1',
'Title 2'
]
},
{
name: 'Countries',
values: [
'India',
'UK'
]
}
];
In above json format I have hard coded those values of Languages,countries and Titles but I have to fetch it from the above model which I have already given.
The json Format which I am getting is following:--
{
"ID": 1,
"DealID": 1,
"Title": "Position1",
"Titles": [
{
"Icon": "hdtv",
"Name": "\nWedding Bells & Farewells\n",
"ID": 12
},
{
"Icon": "hdtv",
"Name": "Delta Farce",
"ID": 5
},
{
"Icon": "hdtv",
"Name": "Doe B: Let Me Find",
"ID": 9
}
],
"Episodes": [
{
"Icon": "episode",
"Name": "Sparkle",
"ID": 4
},
{
"Icon": "episode",
"Name": "Sparks Fly Out",
"ID": 2
},
{
"Icon": "episode",
"Name": "Uploads by Filmi Gaane",
"ID": 7
}
],
"Assets": [
{
"Icon": "file-o",
"Name": "Best of Javed Akhtar - Jukebox 2 - Javed Akhtar Top 10 Hit Songs",
"ID": 10
},
{
"Icon": "file-o",
"Name": "Ep 105 - Sin Say Shun Awards After Party additional image 1",
"ID": 4
},
{
"Icon": "file-o",
"Name": "Ep 105 - Sin Say Shun Awards After Party box cover",
"ID": 3
}
],
"Documents": [],
"Languages": [
{
"Icon": "globe",
"Name": "Albanian",
"ID": 70
},
{
"Icon": "globe",
"Name": "Amharic",
"ID": 96
}
],
"Territories": [],
"Countries": [
{
"Icon": "globe",
"Name": "Afghanistan",
"ID": 2
},
{
"Icon": "globe",
"Name": "Albania",
"ID": 3
},
{
"Icon": "globe",
"Name": "Algeria",
"ID": 4
}
],
"Rights": [
{
"Icon": "leaf",
"Name": "Ancillary",
"ID": 23
},
{
"Icon": "leaf",
"Name": "Finshed Episode Rights",
"ID": 20
},
{
"Icon": "leaf",
"Name": "Format Group - DO NOT USE",
"ID": 63
}
],
"Contributors": [],
"Transmissions": [],
"Available": null
}
It would be best to write a simple parser and transform your data type to JSON - which would additionally allow you to reuse the parser in the future, and convert it to other data types easily for instance.
You could look at the various YAML parsers for inspiration, which would use a similiar technique for your data set's language.
Alternatively you can create a 'hack' and just keep splitting things up if your data format is always of this format, and doesn't allow arbitrary value nesting.
List personel = new List();
var client = new RestClient("your adres");
var request = new RestRequest(Method.GET);
request.AddHeader("Postman-Token", "2893de4a-457e-46a7e8efb025");
request.AddHeader("cache-control", "no-cache");
request.AddHeader("Content-Type", "application/json");
request.AddHeader("token", "a23a80f7-3323-4594056");
IRestResponse response = client.Execute(request);
JObject deger = JObject.Parse(response.Content);
var toplam = deger["data"]["data"].Count();
string jenp = toplam.ToString();
for (int i = 0; i < toplam; i++)
{
Personeller data = new Personeller();
data.Adi = deger["data"]["data"][i]["adi"].ToString();
data.Soyadi = deger["data"]["data"][i]["soyadi"].ToString();
data.tckimlikno = (long)deger["data"]["data"][i]["tckimlikno"];
personel.Add(data);
}

Categories