Is there a way of getting a cleaner JSON out of Couchdb? - json

I am wondering if there is a way to get a cleaner JSON with just the docs out of Couchdb instead of getting it under "rows" and then "doc"
This is the default output
{
"total_rows":1,
"offset":0,
"rows":[
{
"id":"7d9fd5824f9029186c1eec1bda005e75",
"key":"7d9fd5824f9029186c1eec1bda005e75",
"value":{
"rev":"1-f99879f67cfd27685f92c884c236a0fd"
},
"doc":{
"_id":"7d9fd5824f9029186c1eec1bda005e75",
"_rev":"1-f99879f67cfd27685f92c884c236a0fd",
"title":"Hello World",
"messeges":"This is the first messege. Helloo there"
}
}
]
}
This is the desired output:
{
"_id":"7d9fd5824f9029186c1eec1bda005e75",
"_rev":"1-f99879f67cfd27685f92c884c236a0fd",
"title":"Hello World",
"messeges":"This is the first messege. Helloo there"
}
Thanks

It would be useful to see your code. I suspect this is the output of the alldocs api? If you know the ID of the document you want you can use the get api which returns the JSON you want. Otherwise you must loop through the "rows" ie
for (x in results.rows) {...}
and then use x.doc to get your JSON.

Thanks all for the help.
I figured out a way doing it in Node js by using a map function attached to there query
in the nano page they listed it as
alice.list().then((body) => {
body.rows.forEach((doc) => {
console.log(doc);
});
});
instead I used it like this
alice.list().then((body) => {
var result = body.rows.map( (x) => {
return x.doc
});
console.log(result);
});
which works for me.
Still new till couchdb and databases in general.

Related

Best Schema for a Data List in JSON for RestFul API to use in Angular

I've been wondering for some days what kind of scheme would be more appropriate to use a data list in json in a web application.
I'm developing a REST Web Application, and im using Angular for front end, i should order, filter and print these data list also in xml ...
For you what scheme is better and why?
1) {
"datas": [
{ "first":"","second":""},
{ "first":"","second":""},
{ "first":"","second":""}
]
}
2) {
"datas": [{
"data": { "first":"","second":""},
"data": { "first":"","second":""},
"data": { "first":"","second":""}
}]
}
3) [
{ "first":"","second":""},
{ "first":"","second":""},
{ "first":"","second":""}
]
Thanks so much.
The first and third notations are quite similar because the third notation is included in your first.
So the question is "Should I return my datas as an array or should I return an object with a property that contain the array ?
It will depend on either you want to have more information alongside your datas or not.
For exemple, if your API might return an error, you will want to manage it from the front end.
In case of error, the JSON will looks like this :
{
"datas": null,
"error": "An error occured because of some reasons..."
}
At the opposite, if everything goes well and your API actually return the results, it will looks like this :
{
"datas": [
{ "first":"","second":""},
{ "first":"","second":""},
{ "first":"","second":""}
],
"error": null
}
Then your front end can use the error property to manage errors sent from the API.
var result = getDatas(); // Load datas from the API
if(result.error){
// Handle the error, display a message to the user, ...
} else {
doSomething(result.datas); // Use your datas
}
If you don't need to have extra properties like error then you can stick with the third schema.
The second notation is invalid. The datas array will contain only one object which will have one property named data. In this case data is a property that is defined multiple times so the object in the array will contain only the last occurence:
var result = {
"datas": [{
"data": { "first":"a","second":"b"},
"data": { "first":"c","second":"d"},
"data": { "first":"e","second":"f"}
}]
}
console.log("Content of result.datas[0].data : ")
console.log(result.datas[0].data)
Obviously the first option would be easy to use. Once you will access datas it'll give you an array. Any operation (filter, sort, print) on that array will be easy in comparison to anything else. Everywhere you just need to pass datas not datas.data.

Dynamic JSON structure

I am trying to make a JSON-key dynamic with the following data and function:
var jsonData = [ ];
addProcess("Text1", "Text2", jsonData)
function addProcessingPurpose(title, domain, arr) {
arr.push({
"First": title,
domain : {
"subitem": {
"Subsubitem": "text"
}
}
});
}
I get the desired output expect I don't seem to manage setting the keys dynamically from the function parameter. E.g. now it prints "domain" instead of "Text2" which is my desired output. How can this be solved please?
Sorry for the stupid question, solved it myself didn't saw I forgot the [ ] around the key.. Thank you anyway, maybe it can help someone else..

Should I convert JSON to Array to be able to iterate it with v-for?

In the following code I am getting data from server and filling array with them:
Vue.http.post('/dbdata', DataBody).then((response) => {
App.$refs.userContent.rasters_previews_list.$set(response); // putting JSON answer to Component data in userContent
console.log("App.$refs.userContent.rasters_previews_list: ", App.$refs.userContent.rasters_previews_list.length);
}, (response) => {
console.log("Error")
});
Now I am filling. data is declared in var userContent = Vue.extend({. I am using App.$refs.userContent.rasters_previews_list to set it's value, because one man from SO said that there is no other way to get access to constructor. I tried to do output of rasters_previews_list after changing with watch, but here is what I am see. http://img.ctrlv.in/img/16/08/04/57a326e39c1a4.png I really do not understand am I setting it's right way or no. If yes, why I do not see data and see only this crap?
data: function () {
return {
rasters_previews_list: []
}
}
But How I can iterate it with v-for?
<ul v-for="img in rasters_previews_list">
<li>{{img}}</li>
<ul>
This code is display one bullet. So it's look like it's assume that there is one object.
My object in browser console look like:
Object {request: Object, data: Array[10], status: 200, statusText: "OK", ok: true}
Your setting the full response instead of just the data you actually need.
Vue.http.post('/dbdata', DataBody).then((response) => {
App.$refs.userContent.rasters_previews_list.$set(response.data);
console.log("App.$refs.userContent.rasters_previews_list: ", App.$refs.userContent.rasters_previews_list.length);
}, (response) => {
console.log("Error")
});
If this isn't what you are looking for please post a full example.

VueJS - trouble understanding .$set and .$add

I am trying to build an array of objects in VueJS and I am running into some issues with .$set and .$add.
For example, I need the following structure when adding new items/objects:
{
"attendees": {
"a32iaaidASDI": {
"name": "Jane Doe",
"userToken": "a32iaaidASDI",
"agencies": [
{
"name": "Foo Co"
}
]
}
}
}
New objects are added in response to an AJAX call that returns JSON formatted the same as above. Here is my Vue instance:
var vm = new Vue({
el: '#trainingContainer',
data: {
attending: false,
attendees: {}
},
methods: {
setParticipantAttending: function(data)
{
if (data.attending)
{
this.attendees.$add(data.userToken, data);
} else {
this.attendees.$delete(data.userToken);
}
}
}
});
This only works if I start with attendees: {} in my data but when I try attendees.length after adding an attendee, I receive undefined. If I use attendees: [], the new object does not appear to be added. And lastly, if I use .$set(data.userToken, data) it does not add in the 'token':{data..} format required.
What could be the issue here? What is the correct way to use $.add when starting with an empty array of objects?
UPDATE
I found that it works if I set attendees: {} and then, when adding a new object,
if (data.userToken in this.attendees) {
this.attendees.$set(data.userToken, data);
} else {
this.attendees.$add(data.userToken, data);
}
Not sure if there is a better way to accomplish this.
If you set attendees to an empty object ({}) it will not have a length attribute. That attribute is on Arrays.
If you set attendees to an empty array ([]) then you need to use $set (or really, I think you want .push()) – $add is intended for use on objects not on arrays.
I'm not quite following your last question – could you add more context?
EDIT 2:
The answer below was for Vue 1.x. For Vue 2.x and greater use:
this.$set(this.attendees, data.userToken, data);
More information here: https://v2.vuejs.org/v2/api/#Vue-set
EDIT:
Responding to your update, you should be able to just use $set in all cases. I.e. just do this:
this.attendees.$set(data.userToken, data);
As of version 0.6.0, this seems to be the correct way:
this.someObject = Object.assign({}, this.someObject, { a: 1, b: 2 })
http://vuejs.org/guide/reactivity.html#Change_Detection_Caveats

Datatables process json response multiple objects

Im using Datatables Jquery plugin to do a bit of work, but i havent been able to understand how to process the Json response im getting from the server .
I get this response:
"aaData":[
[
{
"idTreatment":23,
"treatment":"Hospitalización",
"directions":"Directions",
"active":"1"
},
{
"idCIE10":1,
"cieCode":"A00",
"diagnostic":"COLERA",
"description":null,
"lastUsed":1386649580000,
"active":1
}
],
[
{
"idTreatment":27,
"treatment":"Antibiótico",
"directions":null,
"active":"1"
},
{
"idCIE10":1,
"cieCode":"A00",
"diagnostic":"COLERA",
"description":null,
"lastUsed":1386649580000,
"active":1
}
],
[
{
"idTreatment":33,
"treatment":"Hidratación Oral",
"directions":"Directions",
"active":"1"
},
{
"idCIE10":1,
"cieCode":"A00",
"diagnostic":"COLERA",
"description":null,
"lastUsed":1386649580000,
"active":1
}
]
]
}
I have been trying to use mData or mRender, but im not familiarized with datatables yet, so i would be really grateful if someone could thell me how can in print this in a table on html
thanks in advance
this javascript fucntion is the one im using to initialize the table, im trying to use aoColumns based on examples but im not sure if this is the best option; also based on example im using mData, to show just 2 columns for test, as you can see im trying to acces the "array" or the json response using the objects field names, but when the page is rendering theres a warning saying that it cant find the field.
function initializeTreatmentsTable(id){
treatmentsTable = $('#treatmentsTable').dataTable( {
"bSort":false,
"sAjaxSource":"./diagnosticTreatment",
"fnServerParams": function ( aoData ) { aoData.push( {name:"diagnosticId",value:id} ); },
"aoColumns": [
{ "mData": "idTreatment" },
{ "mData": "treatment" }
]
});
Well after looking several times over the API in the official website datatables.net i came to the conclusion that i had to test out.
If my problem isn't clear i will explain it again.
i have a table, and that table's data is obtained by a ajax request and a json response, the json response is a array of object but the objects themselves are composed of at least 2 objects ( {[[object1][object2]],[[object1][object2]]} ) so accessing them with mData was impossible at least for me, and the solution was so simple that i wonder i never tried, i just had to use mRender and a function.
function initializeTreatmentsTable(id){
treatmentsTable = $('#treatmentsTable').dataTable( {
"bSort":false,
"sAjaxSource":"./diagnosticTreatment",
"fnServerParams": function ( aoData ) { aoData.push( {name:"diagnosticId",value:id} ); },
"aoColumns": [
{ "bVisible": false,
"mRender": function(data,type,full){
return data.idTreatment;}
},
{ "mRender": function(data,type,full){
return full[0].treatment;
} }
]
});
The function above its the one im using to initialise the table for the first time, i got the problem that i just wanted 2 field from the first object and none from the second one, but i dont now how to do it, so i used the "full" parameter that contains the whole json response, and accesed it.
This might not be the best answer but it did the work for me, so i hope that if someone know how to improved it , feel free to do it, or so just comment , and i also hope this can help someone else.