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
}
Related
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);
I'm trying to pull out the individual images in the "images" object below under "details" section.
Seem to just be getting nothing printing out. Looking for the correct way to pull within the details.images.image1,2, or 3.
Here is the JSON data I'm working with so far:
{
"books": [
{
"title": "title 1",
"image": "/image1.jpg"
},
{
"title": "title 2",
"image": "/image2.jpg"
}
],
"details": [
{
"author": "book author",
"name": "Book name",
"price": 34.99,
"publisher": "Penguin Books",
"images": [
{
"image1": "/image1.jpg",
"image2": "/image2.jpg",
"image3": "/image3.jpg"
}
]
}
]
}
Also here is the JSON call I'm making in a Book component:
{staticdata.details.map(detail => (
<Book
book_name={detail.author}
book_price={detail.price}
image={detail.images.image1}
/>
))}
Here's an example of accessing those nested properties and logging them to the console. It appears your attempt was mostly correct, but images is an array.
const data = {
"books": [
{
"title": "title 1",
"image": "/image1.jpg"
},
{
"title": "title 2",
"image": "/image2.jpg"
}
],
"details": [
{
"author": "book author",
"name": "Book name",
"price": 34.99,
"publisher": "Penguin Books",
"images": [
{
"image1": "/image1.jpg",
"image2": "/image2.jpg",
"image3": "/image3.jpg"
}
]
}
]
}
data.details.map(detail => {
console.log(detail.author, detail.price, detail.images[0].image1);
});
I have a document that resembles:
[
{
"subscriberid": "4355",
"Title": "Miss",
"FirstName": "FirstName",
"LastName": "LastName",
"EmailAddress": "thisisanemail#email.com",
"Mobile": "",
"Postcode": "B1 3qq",
"Gender": "",
"SubscribeDate": "2015-08-12 10:58:29",
"Birthday": "31-5-1985",
"Kids": "no",
"Kidsages": "",
"Student": "no",
"Favourite": "1113111",
"attendreason": "Array",
"MarketingOptIn": "Y",
"Source": "WEBSITE",
"Login": [
{
"subscriberid": "4355",
"Created_at": "2017-05-18 10:09:44",
"IPaddress": "1.1.2.3"
}
]
},
{
"subscriberid": "125",
"Title": "",
"FirstName": "FirstName2",
"LastName": "LastName2",
"EmailAddress": "thisisalsoanemail#email.com",
"Mobile": "",
"Postcode": "tn39 4de",
"Gender": "",
"SubscribeDate": "2015-12-02 17:21:18",
"Birthday": "13-3-1922",
"Kids": "no",
"Kidsages": "",
"Student": "no",
"Favourite": "8108200",
"attendreason": "Date",
"MarketingOptIn": "Y",
"Source": "FACEBOOK",
"Vouchers": [
{
"subscriberid": "213",
"Created_at": "2017-05-18 08:57:47",
"Source": "some website",
"offer": "50offMains",
"name": "50% off Mains"
}
],
"Login": [
{
"subscriberid": "123",
"Created_at": "2017-05-18 07:57:46",
"IPaddress": "1.2.3.4"
}
]
}
]
And I'm trying to turn it into a CSV, automatically. Normally this would be a very simple script with json2csv, but for some reason this time I'm having an issue that I'm struggling to troubleshoot. My file is being created, but with headers only and no data.
I read the docs on https://github.com/zemirco/json2csv and I'm thinking I would use dot notation for the fields but due to how it's setup, I'm unsure what would preceed the dot?
I tried CLI version and an actual JS Version but same deal. All I get is the headers. As you'll see in the script, I only care about parts of the JSON Document, but even if I try to do it all, I still only get the headers. My previous versions have all used glob, but the CLI and pointing directly to the file still nets the same result.
var json2csv = require('json2csv');
var fs = require('fs');
var glob = require('glob');
let fields =
[
"subscriberid",
"Title",
"FirstName",
"LastName",
"EmailAddress",
"Mobile",
"Postcode",
"Gender",
"SubscribeDate",
"Birthday",
"Kids",
"Kidsages",
"Student",
"Favourite",
"attendreason",
"MarketingOptIn",
"Source"
];
let dataInput = glob("path/**/toFile.txt");
var csv = json2csv({ data: dataInput, fields: fields });
fs.writeFile('output.csv', csv, function(err) {
if (err) throw err;
console.log('file saved');
});
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 }
I have the following documents
{
"_id": "id",
"_rev": "123456",
"author": "john",
"views": "3",
},
{
"_id": "id",
"_rev": "123456",
"author": "jake",
"views": "5",
},
{
"_id": "id",
"_rev": "123456",
"author": "jake",
"views": "6",
},
{
"_id": "id",
"_rev": "123456",
"author": "john",
"views": "1",
},
{
"_id": "id",
"_rev": "123456",
"author": "jake",
"views": "7",
},
{
"_id": "id",
"_rev": "123456",
"author": "john",
"views": "10",
}
Lets suppose that these are comments and I would like to get the 2 most viewed comments by user.
How can I do that in CouchDB?
In any other sql database I could perform 2 queries with limit 2 and then merge the results.
If you have an array with that data in JavaScript you can simply use the sort method:
var a = [{...}, {...}, {...}];
a.sort(function(a, b) {
return b.views - a.views;
});
console.log(a[0]) //{ "_id": "id", "_rev": "123456", "author": "john", "views": "10" }
console.log(a[1]) //{ "_id": "id", "_rev": "123456", "author": "jake", "views": "7" }
If you want to only have the to most viewed records you can use the slice method
var a = [...];
a.sort(...);
a = a.slice(0, 2);
I guess you could just use this map:
function (doc) {
emit([doc.author, -doc.views], null);
}
without the reduce. Query with options ?startkey=['john']&limit=2 should result with something like:
{"total_rows":5,"offset":0,"rows":[
{"id":"id1","key":["john",-10],"value":null},
{"id":"id2","key":["john",-3],"value":null}
]}
Note the - sign when emitting doc.view to get biggest view count. You can also use descending=true option, but it will also reverse the order of the author string. This is not natural order for strings and you might need that in the future ;)