I'm trying to get the position in array of the first object so i can delete it with a function. The problem is: i don't know how to get the "index"value.
{
"2": {
"nome": "sou1",
"email": "adsa#lala.com",
"gênero": "masculino",
"id": 1,
"pos": 0
},
"3": {
"nome": "sou1",
"email": "adsa#lala.com",
"gênero": "masculino",
"id": 1,
"pos": 1
}
}
In this case, my output would be 2.
You can try the below
var someObject={
"2": {
"nome": "sou1",
"email": "adsa#lala.com",
"gênero": "masculino",
"id": 1,
"pos": 0
},
"3": {
"nome": "sou1",
"email": "adsa#lala.com",
"gênero": "masculino",
"id": 1,
"pos": 1
}};
console.log(Object.keys(someObject)[0]);
delete someObject[Object.keys(someObject)[0]];
console.log(someObject);
There is no ordering in JSON objects.
However, for your use case (if I correctly understand that), you can convert the JSON object into an array doing...
const someObject = {
a: "A",
b: "B",
c: "C"
}
const keys = Object.keys(someObject);
console.log(keys); // array of keys
let arr = [];
for(key of keys) {
arr.push(someObject[key]);
}
console.log(arr); // array of objects
...where the index of an element in the keys array (a key in your original JSON object) will be identical to the index of an element in the arr array (the corresponding value for that key in your original JSON object) which it maps to in your original JSON object, in a way giving you what you probably are looking for. Then you can access them using the array indices.
Hope this helps :)
Related
Thank you aspok for your help!
My goal is to get my list to be [3, 3, 4] and then get a count of unique values within it. Can anyone point me in the right direction for doing this?
My script consumes a JSON and puts all F4211_LNID values into a list. [3.1, 3.9, 4]. I need to now round all decimal places down.
I'm not sure if it's doable, but I am trying to use Math.floor(intListItems) to round my array values down. When I try this I receive the following error: Exception No signature of method: static java.lang.Math.floor() is applicable for argument types: (ArrayList) values: [[3.1, 3.9, 4]] Possible solutions: floor(double), log(double), find(), macro(groovy.lang.Closure), acos(double), cos(double)
I see my simplified list in the error, but I can't get it to round down and not sure what the error means.
(UPDATED) My Working Groovy
// Read Input Values
String aInputJson = aInputMap.InputJson ?: "{}"
// Initialize Output Values
def intListItems = []
def uniqueCount = 0
// Parse JSON
def json = new JsonSlurper().parseText( aInputJson )
// Determine Row Numbers
def rowset = json?.fs_DATABROWSE_F4211?.data?.gridData?.rowset
intListItems = rowset.collect{ Math.floor(it.F4211_LNID) }
intListItems.unique()
uniqueCount = intListItems.size()
JSON I am using.
{
"fs_DATABROWSE_F4211": {
"title": "Data Browser - F4211 [Sales Order Detail File]",
"data": {
"gridData": {
"id": 58,
"fullGridId": "58",
"rowset": [
{
"F4211_LNTY": "S",
"F4211_CPNT": 0,
"F4211_MCU": " 114000",
"F4211_DSC2": "NAS133N3EK166",
"F4211_NXTR": "580",
"F4211_LNID": 3.1,
"F4211_DOCO": 2845436
},
{
"F4211_LNTY": "S",
"F4211_CPNT": 0,
"F4211_MCU": " 114000",
"F4211_DSC2": "NAS133N3EK166",
"F4211_NXTR": "580",
"F4211_LNID": 3.9,
"F4211_DOCO": 2845436
},
{
"F4211_LNTY": "S",
"F4211_CPNT": 0,
"F4211_MCU": " 114000",
"F4211_DSC2": "NAS133N3EK166",
"F4211_NXTR": "580",
"F4211_LNID": 4,
"F4211_DOCO": 2845436
}
],
"summary": {
"records": 1,
"moreRecords": false
}
}
},
"errors": [],
"warnings": []
},
"currentApp": "DATABROWSE_F4211",
"timeStamp": "2000-06-01:09.42.02",
"sysErrors": []
}
You are getting the error Exception No signature of method: static java.lang.Math.floor() is applicable for argument types: (ArrayList) because there is no version of Math.floor() that accepts a List as a parameter.
Instead, you need to call Math.floor() on each individual item in the list. The easiest way to do this is in the collect { } call you are already doing.
def flooredList = rowset.collect { Math.floor(it.F4211_LNID) }
assert flooredList == [3.0, 3.0, 4.0]
I have an array similar than this one, called websiteproducts:
[{
"memberid": 280,
"state": "AL",
"product": "1",
"deleteProduct": 1,
"waitingDays": 0
},
{
"memberid": 280,
"state": "AL",
"product": "2",
"deleteProduct": 1,
"waitingDays": 0
},
{
"memberid": 280,
"state": "AL",
"product": "3",
"deleteProduct": 1,
"waitingDays": 0
},
{
"memberid": 280,
"state": "AL",
"product": "4",
"deleteProduct": 0,
"waitingDays": 0
}
]
And Im trying to delete all objects that have "deleteProduct" = 1 as follows:
for (let i = 0; i < websiteproducts.length; i++) {
if (websiteproducts[i].deleteProduct == 1) {
websiteproducts.splice(i, 1)
}
}
But only the first object is deleted.
I believe it has to do with the fact that Im deleting the item from the array on the fly.
But this one works, when copying the objects to a new array:
let finalProducts = []
for (let i = 0; i < websiteproducts.length; i++) {
if (websiteproducts[i].deleteProduct != 1) {
finalProducts.push(websiteproducts[i])
}
}
Is there a way to delete the objects straight from the array through a loop, without having to create a second array?
Thanks.
You can use the filter function on the array, it only returns the elements that meet the condition.
let finalProd = websiteproducts.filter(prod => prod.deleteProduct != 1)
You don't have to use a loop at all. You can use Array.prototype.filter().
This returns a new array with the filtered elements removed:
const filtered = websiteproducts.filter(product => product.deleteProduct != 1);
You must decrement the index variable after splice like this :
websiteproducts.splice(i, 1);
i--;
I have a nested dictionary with keys and values as shown below.
j = {
"app": {
"id": 0,
"status": "valid",
"Garden": {
"Flowers":
{
"id": "1",
"state": "fresh"
},
"Soil":
{
"id": "2",
"state": "stale"
}
},
"BackYard":
{
"Grass":
{
"id": "3",
"state": "dry"
},
"Soil":
{
"id": "4",
"state": "stale"
}
}
}
}
Currently, I have a python method which returns me the route based on keys to get to a 'value'. For example, if I want to access the "1" value, the python method will return me a list of string with the route of the keys to get to "1". Thus it would return me, ["app","Garden", "Flowers"]
I am designing a service using flask and I want to be able to return a json output such as the following based on the route of the keys. Thus, I would return an output such as below.
{
"id": "1",
"state": "fresh"
}
The Problem:
I am unsure on how to output the result as shown above as I will need to parse the dictionary "j" in order to build it?
I tried something as the following.
def build_dictionary(key_chain):
d_temp = list(d.keys())[0]
...unsure on how to
#Here key_chain contains the ["app","Garden", "Flowers"] sent to from the method which parses the dictionary to store the key route to the value, in this case "1".
Can someone please help me to build the dictionary which I would send to the jsonify method. Any help would be appreciated.
Hope this is what you are asking:
def build_dictionary(key_chain, j):
for k in key_chain:
j = j.get(k)
return j
kchain = ["app","Garden", "Flowers"]
>>> build_dictionary(kchain, j)
{'id': '1', 'state': 'fresh'}
In doClient.scan() is there any way to set the count of elements stored in a particular node?
As per the below example i need to add a new node "questionCount" to the below result which should contain the total number of reference_id in node questionList. is there any way other than iterating the result and adding a new node?
Expected Output
{
"status": 1,
"data": [
{
"questionList": [
{
"reference_id": "0df55215-90de-407a-b077-7017924556d3"
},
{
"reference_id": "0df55215-90de-407a-b077-7017924556d3"
},
{
"reference_id": "0df55215-90de-407a-b077-701997924556d3"
}
],
"testName": "sample test231s",
"testId": "2e97e40c-82cb-4126-9f47-b6a93687a59c",
"questionCount": 3
}
]
}
As you add questions to questionList with list_append, you could also increment the questionCount attribute with an UpdateExpression SET data.questionList = list_append(data.questionList, :newQuestion), ADD questionCount :one and ExpressionAttributeValues {":newQuestion": {"reference_id": "blah"}, ":one": 1}.
I have stored my Data in the give formate in AreangoDB, My collection name in DSP:
"data": {
"1": [ {"db_name": "DSP"}, {"rel": "2"} ],
"2": [ {"rel_name": "DataSource"}, {"tuple": "201"}, {"tuple": "202"}, {"tuple": "203"} ],
"201": [ {"src_id": "Pos201510070"}, {"src_name": "Postgres"}, {"password": "root"}, {"host": "localhost"}, {"created_date": "20151007"}, {"user_name": "postgres"}, {"src_type": "Structured"}, {"db_name": "postgres"}, {"port": "None"} ],
"202": [ {"src_id": "pos201510060"}, {"src_name": "Postgres"},{"password": "root"}, {"host": "localhost"}, {"created_date": "20151006"}, {"user_name": "postgres"}, {"src_type": "Structured"}, {"db_name": "DSP"}, {"port": "5432"} ],
"203": [ {"src_id": "pos201510060"}, {"src_name": "Postgres"}, {"password": "root"}, {"host": "localhost"}, {"created_date": "20151006"}, {"user_name": "postgres"},{"src_type": "Structured"},{"db_name": "maindb"},{"port": "5432"} ]
}
I am executing a query with the above data in the following format:
FOR p IN NestedDSP
LET attributes = ATTRIBUTES(p)
FOR attribute IN attributes
LET key = ATTRIBUTES(attribute)[0]
LET value = attribute[key]
RETURN { subject: attribute, predicate: key, object: value }
When I submit my query to ArangoDB, it returns the response as:
Warnings:
[1542], 'invalid argument type in call to function 'ATTRIBUTES()''
[1542], 'invalid argument type in call to function 'ATTRIBUTES()''
[1542], 'invalid argument type in call to function 'ATTRIBUTES()''
[1542], 'invalid argument type in call to function 'ATTRIBUTES()''
Result:
[
{
"subject": "data",
"predicate": null,
"object": null
},
{
"subject": "_id",
"predicate": null,
"object": null
},
{
"subject": "_rev",
"predicate": null,
"object": null
},
{
"subject": "_key",
"predicate": null,
"object": null
}
]
Please tell me what is the problem with this query, and why the answer is like the above..I am working in ArangoDB-2.7.3-win64.
Thanks
Let me demonstrate how to construct such a complex query digging deep into nested data structures. I start out taking the outer parts of the query, to have an inner result:
FOR p IN NestedDSP
LET attributes = ATTRIBUTES(p)
FOR attribute IN attributes
RETURN attribute
which gives me:
[
"data",
"_rev",
"_key",
"_id"
]
So lets dive deeper into the next layer. I guess you're only interested in the values present underneath data key right? so we pick p.data:
FOR p IN NestedDSP
LET attributes = ATTRIBUTES(p.data)
FOR attribute IN attributes
RETURN attribute
which then gives me the keys for your next inner array:
[
"203",
"202",
"201",
"2",
"1"
]
We now explore what we find attached to these nodes:
FOR p IN NestedDSP
LET attributes = ATTRIBUTES(p.data)
FOR oneAttribute IN attributes
LET keys = p.data[oneAttribute]
RETURN keys
Its Again an array, which we need to iterate into using a FOR loop over keys:
[
[
{
"src_id" : "pos201510060"
},
{
"src_name" : "Postgres"
}, ...
We add this additional FOR-loop:
FOR p IN NestedDSP
LET attributes = ATTRIBUTES(p.data)
FOR oneAttribute IN attributes
LET keys = p.data[oneAttribute]
FOR key IN keys
RETURN key
we get the inner most objects:
[
{
"src_id" : "pos201510060"
},
{
"src_name" : "Postgres"
},
{
"password" : "root"
},
...
You wanted to use the ATTRIBUTES function, but the objects only have one member, so we can access [0]:
FOR p IN NestedDSP
LET attributes = ATTRIBUTES(p.data)
FOR oneAttribute IN attributes
LET keys = p.data[oneAttribute]
FOR key IN keys
LET keyAttributes=ATTRIBUTES(key)
RETURN keyAttributes
Which gives us the object keys, one per inner most object:
[
[
"src_id"
],
[
"src_name"
],
We inspect whether we now get only the object keys of the inner most structure; we pick the variable names a little more clever than above:
FOR p IN NestedDSP
LET attributes = ATTRIBUTES(p.data)
FOR oneAttribute IN attributes
LET pairs = p.data[oneAttribute]
FOR onePair IN pairs
LET pairKey=ATTRIBUTES(onePair)[0]
RETURN pairKey
YES:
[
"src_id",
"src_name",
"password",
"host",
...
So now its time to construct the results object as you wanted them:
FOR p IN NestedDSP
LET attributes = ATTRIBUTES(p.data)
FOR oneAttribute IN attributes
LET pairs = p.data[oneAttribute]
FOR onePair IN pairs
LET pairKey=ATTRIBUTES(onePair)[0]
RETURN { subject: oneAttribute, predicate: pairKey, object: onePair[pairKey] }
The subject is the number identifying the outermost item, the predicate is the object key, and the object is the value in it:
[
{
"subject" : "203",
"predicate" : "src_id",
"object" : "pos201510060"
},
{
"subject" : "203",
"predicate" : "src_name",
"object" : "Postgres"
}
Which is hopefully what you wanted?