CouchDB JSon response customization - database

I'm storing addresses data in Couchdb, and am looking for a way to get an array of just the values, instead of key: value for every record.
This is the current response:
{"total rows": 2438, "offset": 0, "rows":[
{"id": "ec5de6de2cf7bcac9a2a2a76de5738e4", "key": "user_298774", "value": {"city": "Milano", "address":"Corso Como, 42b"},
{"id": "a2a2a76de573ae4ec5de6de2cf7bcac9", "key": "user_276341", "value": {"city": "Vicenza", "address":"Via Quinto Sella, 118"}
... (etc).
]}
I only really need:
[{"city": "Milano", "address":"Corso Como, 42b"},
{"city": "Vicenza", "address":"Via Quinto Sella, 118"},
...]
I really need to minimize the usage of bandwidth that a JSON response consumes. I can't seem to find a way to transform the view into a simple array. Suggestions?

The response you are getting conforms to the Couch's REST based protocol. To reformat it two methods are provided: show functions and list functions. Basic idea is the same, but the first is suitable for retrieval documents and the list function is for you!
The list function runs the query inside the server and send the output arbitrary transformed with your JS code. API you will need is simple:
Fetch each record from the view with the getRow() function.
Export to the string (containing JSON) your JS object obj with toJSON(obj).
Send the output to the client with send(json).
If the map/reduce view URL with data is /mydb/_design/myapp/_view/mydocs-by-user and the list function name is mylist get the reformatted result to the client with the URL /mydb/_design/myapp/_list/mylist/mydocs-by-user.
Please refer to the list function documentation cited above and the chapter in the Guide for the longed tutorial.

Related

Iterating a JSON array in LogicApps

I'm using a LogicApp triggered by an HTTP call. The call posts a JSON message which is a single row array. I simply want to extract the single JSON object out of the array so that I can parse it but have spent several hours googling and trying various options to no avail. Here's an example of the array:
[{
"id": "866ef906-5bd8-44d8-af34-0c6906d2dfd7",
"subject": "Engagement-866ef906-5bd8-44d8-af34-0c6906d2dfd7",
"data": {
"$meta": {
"traceparent": "00-dccfde4923181d4196f870385d99cb84-52b8333f100b844c-00"
},
"timestamp": "2021-10-19T17:01:06.334Z",
"correlationId": "866ef906-5bd8-44d8-af34-0c6906d2dfd7",
"fileName": "show.xlsx"
},
"eventType": "File.Uploaded",
"eventTime": "2021-10-19T17:01:07.111Z",
"metadataVersion": "1",
"dataVersion": "1"
}]
Examples of what hasn't worked:
Parse JSON on the array, error: InvalidTemplate when specifiying an array as the schema
For each directly against the http output, error: No dependent actions succeeded.
Any suggestions would be gratefully received.
You have to paste the example that you have provided to 'Use sample payload to generate schema' in the Parse JSON Connector and then you will be able to retrieve each individual object from the sample payload.
You can extract a single JSON object from your array by using its index in square brackets. E.g., in the example below you'd need to use triggerBody()?[0] instead of triggerBody(). 0 is an index of the first element in the array, 1 - of the second, and so on.
Result:

HTTP Request logic app - parse values from array name, value pair

I am POSTing valid JSON to a logic app and the request body is a simple set of name/value pairs in JSON format. I use parse JSON action to turn the JSON into a variable. (I am not sure if this is absolutely required, or if I can reference the http body directly without a JSON object).
[
{
"name": "fullname",
"value": "joe schmoe"
},
{
"name": "email",
"value": "joeschmoe#acme.com"
}
]
All I need to do (and this is driving me nuts) is create two variables, one containing the value of the email field and one containing the value of the fullname field.
As soon as I try to use the output value value, the logic app replaces my action with a For Each action, and then I try to to assign item().value[0] or item().value[1] to a variable without luck.
I have read dozens of examples online, but of course they all seem to be parsing JSON where there is largely unique elements in the name:value pairs.
While this is a bit of a newb question, I'm confused and need advice.
Thank you.
I used a parseJSON action to ensure I have a varaible containing the JSON array.
I then referenced the array value with (explained):
"from the body of the output from the Parse JSON action, refernce the first record in the set (fullname) and then the value of that record, the value 'joe schmoe'"
#{body('Parse_JSON')[0]['value']} (returns fullname)
Email is similar, just 2nd record in the collection:
#{body('Parse_JSON')[1]['value']} (returns email address)

Does Flask map JSON Array object to a Python string?

In my Flask server I am receiving a JSON-encoded parameter which is being sent via an HTTP POST from the client application.
Here is an example of what the JSON object looks like. For simplicity, I have kept only the first 2 entries, but the full object contains many more such entries.
[
{
"id": 1,
"start": 7.85,
"end": 9.813,
"text": "Θέλω να",
"words": [
"Θέλω",
"να"
],
"isBeingEditedByUser": false,
"translatedText": "I want to"
},
{
"id": 2,
"start": 9.898,
"end": 13.055,
"text": "Από κάτι το πήραν πολύ άσχημα ο οπαδός του Ολυμπιακού",
"words": [
"Από",
"κάτι",
"το",
"πήραν",
"πολύ",
"άσχημα",
"ο",
"οπαδός",
"του",
"Ολυμπιακού"
],
"isBeingEditedByUser": false,
"translatedText": "Something very bad for Olympiacos fan"
}
]
My understanding is that this JSON structure corresponds to an Array (in Javascript) or a List in Python. In this case, it is an array containing two elements, where each element is itself an object.
However, when I try to use the object on the Flask side, it seems that it has been mapped to a string (rather than a List). Is this normal behavior? I have not been able to find any documentation which states that this is the normal mapping. I would have expected the JSON object to be mapped to a Python List object instead, but this is not happening.
I know that I can use python.loads() myself to convert the string into the appropriate List structure, but I did not expect to have to do this and want to make sure that I am not misunderstanding something here.
Here is a snippet of code which shows the relevant portion in my Flask function:
#app.route('/update_SRT_file', methods=['POST'])
def update_SRT_file():
# Validate the request body contains JSON
if request.is_json:
json_obj = request.get_json()
eprint("update_SRT_file: received JSON object: ")
eprint("Type of received object is", type(json_obj));
else:
eprint("update_SRT_file: Request was not JSON ")
Here is what gets printed out:
23:12:12.771824 update_SRT_file: received JSON object:
23:12:12.771878 Type of received object is **<class 'str'>**
After more investigation, the problem was occuring because the client was JSON encoding the data twice. Upcon removing the additional encoding, it was found that now Flask correctly maps the incoming JSON Array to a python List structure.
Your POST request is sending the JSON as raw text. Flask then receives it as raw text in the request body. Some web application frameworks might automatically parse the text into a JSON-like object or data structure, but Flask does not, at least not out of the box.

Append sensor data into document in Couchbase database

We are a group of people writing a bachelor-project about storing sensor data into a noSQL-database, and we have chosen couchbase for this.
We want to store quite a few data in the same document, one document per day, per sensor, and we want to append new sensor data witch comes in every minute.
But unforunatly, we are not able to append new data into existing document without overwriting the existing data.
The structure for the documents is:
DocumentID: Sensor + date, ie: KitchenTemperature20180227
{
"topic": "Kitchen/Temp",
"type": "temperature",
"unit": "DegC"
"20180227130400": [
{
"data": "24"
}
],
..............
"20180227130500": [
{
"data": "25"
}
],
}
We are all new to couchbase and NoSql-databases, but eager to learn and understand how we the best way should implemet this.
We've tried upsert, insert and update commands, but they all overwrite the existing document or won't execute because the document already exists. As you can see, we have some top-level information, like topic, type, unit. The rest should be data coming in every minute and appended to the existing document.
Help on how to proceed would be very appriciated.
Best regards, Kenneth
In this case you can use the subdocument API. This allows you to modify portions of a document based on a "path". This image gives the idea for getting a subdocument.
You can mutate subdocuments as well. Look at the subdocument API documentation for Couchbase. There are also blog posts that go through examples in Java and Go on the Couchbase blog site.

How to fetch data from couchDB using couch api?

Instead keys and IDs alone, I want to get all the docs via couch api. I have tried with GET "http://localhost:5984/db-name/_all_docs" but it returned
{
"total_rows":4,
"offset":0,
"rows":[
{"id":"11","key":"11","value":{"rev":"1-a0206631250822b37640085c490a1b9f"}},
{"id":"18","key":"18","value":{"rev":"30-f0798ed72ceb3db86501c69ed4efa39b"}},
{"id":"3","key":"3","value":{"rev":"15-0dcb22bab2b640b4dc0b19e07c945f39"}},
{"id":"6","key":"6","value":{"rev":"4-d76008cc44109bd31dd32d26ba03125d"}}
]
}
From the documentation
for the below request it will send the data as we expected but it requires set of keys in request.
POST /db/_all_docs HTTP/1.1
{
"keys" : [
"11",
"18"
]
}
Thanks in advance.
The _all_docs endpoint is actually just a system-level view that uses the _id field as the index. Thus, any parameters that you can use for views also apply here.
If you read the documentation further, you'll find that adding the parameter include_docs=true to your view will include the original documents in the results. The documents will be added as the doc field alongside id, value and rev.

Resources