Linq to Json using Like Clause - json

I've got an MVC 3 web app and am returning a JSON object which I would like to use Linq against to limit the result returned to the client jquery.
The Json response takes the following structure:
{
"Data": {
"Items": [
{
"Result": {
"Id": "e2ba4912-c387-4f54-b55e-06742a6858db",
"Name": "SomeOtherSetting",
"Value": "500",
"Archived": false
},
"Result": {
"Id": "17c27584-cea8-42c2-b6c4-0b30625ac3ce",
"Name": "Setting2",
"Value": "600",
"Archived": false
},
"Result": {
"Id": "17c27584-cea8-42c2-b6c4-0b30625ac3ce",
"Name": "Setting3",
"Value": "700",
"Archived": false
}
}]
}
}
....
I need to return or grab just the json items that have a Name like 'Setting' for example. In the example, this would return just the 2 Json nodes.
My Linq is very limited and what I have is: Settings is where the Json response is stored.
NewtonSoft.Json.Linq.JObject data = NewtonSoft.Json.Linq.JObject.Parse(Settings);
var result = from p in data["Data"]["Items"].Children()
where (p["Result"]["Name"].Contains("Expenses.Help.Tip"))
select new { Name = (string)p["Result"]["Name"], Value = (string)p["Result"]["Value"] };
When I run this I get nothing in my result. Can anyone help and tell me what I'm doing wrong?
Thanks.

Well, I'm not a Json specialist, but I think your Json structure has some problems.
I tried an online parser, and parsing took only the third result... (try to copy past your code in the left window, and look at JS eval.
Instead of
"Items": [
{
"Result": {
},
"Result": {
},
"Result": {
}
}]
you should have each element of Items array (each 'Result') into {}.
"Items": [
{
{"Result": {
}
},
{"Result": {
}
},
{"Result": {
}
}]
I got it to work by changing your Json file to
{
"Data": {
"Items": [
{
"Result": {
"Id": "e2ba4912-c387-4f54-b55e-06742a6858db",
"Name": "SomeOtherSetting",
"Value": "500",
"Archived": false
}
},
{
"Result": {
"Id": "17c27584-cea8-42c2-b6c4-0b30625ac3ce",
"Name": "Setting2",
"Value": "600",
"Archived": false
}
},
{
"Result": {
"Id": "17c27584-cea8-42c2-b6c4-0b30625ac3ce",
"Name": "Setting3",
"Value": "700",
"Archived": false
}
}]
}
}
using
var data = JObject.Parse(test)["Data"]["Items"].Children()
.Where(m => m["Result"]["Name"].Value<string>().Contains("Setting"))
.Select(m => new
{
Name = m["Result"]["Name"].Value<string>(),
Value = m["Result"]["Value"].Value<int>()
})
.ToList();

Related

Looping and searching through JSON using PowerShell

I have a JSON file that has following contents:
{
"status": "UP",
"details": {
"graphDBCheck": {
"status": "UP"
},
"ds": {
"status": "UP",
"details": {
"total": 100,
"free": 50,
"threshold": 30
}
},
"db": {
"status": "UP",
"details": {
"ADS": {
"status": "UP",
"details": {
"database": "Influx",
"hello": "Hello"
}
},
"EARDS": {
"status": "UP",
"details": {
"database": "Oracle",
"hello": "Hello"
}
},
"EFRDS": {
"status": "UP",
"details": {
"database": "Sybase",
"hello": "Hello"
}
}
}
}
}
}
I need to be able to transform this into a CSV file that has each element's name as header and it's status or value as the next row. First "status" would have column name "API_Status"
For instance:
API_Status,graphDBCheck,ds,db,ADS,EARDS,EFRDS
UP,UP,UP,UP,UP,UP,UP
Challenge here is to make this dynamic so the output will always include any other element added that has "status" in it.
I tried this and it works but I need a dynamic way do to this:
$x = Invoke-RestMethod $url -Verbose:$VerbosePreference
[pscustomobject][ordered]#{
'API_Status' = $x.status
'db' = $x.details.db.status
'ds' = $x.details.diskspace.status
'ds_Total' = $x.details.ds.details.total
'ds_Free' = $x.details.ds.details.free
'graphDBCheck' = $x.details.graphDBCheck.status
'ADS' = $x.details.db.details.auroraDataSource.status
'EARDS' = $x.details.db.details.EARDS.status
'EFRDS' = $x.details.db.details.edsFirstRowsDataSource.status
}
In an ideal world, the json would be structured like this, as an expandable array with uniform properties.
[
{
"name": "API_Status",
"status": "UP"
},
{
"name": "graphDBCheck",
"status": "UP"
},
{
"name": "ds",
"status": "UP"
},
{
"name": "db",
"status": "UP"
},
{
"name": "ADS",
"status": "UP"
},
{
"name": "EARDS",
"status": "UP"
},
{
"name": "EFRDS",
"status": "UP"
}
]
Or as a csv:
name,status
API_Status,UP
graphDBCheck,UP
ds,UP
db,UP
ADS,UP
EARDS,UP
EFRDS,UP
There's plenty of other posts about looping through powershell properties Iterate over PSObject properties in PowerShell or looping through json properties: Iterating through a JSON file PowerShell

how to remove json element using json parse in logic app?

Input json -
{
"data": {
"Testresults": [
{
"mydata": {
"id": "111",
"uri": "url",
"type": "demo"
},
"name": "",
"address": "",
in side Parse Json schema added as below -
{
"properties": {
"data": {
"properties": {
"Testresults": {
"items": {
"properties": {
"name": {
"type": "string"
},
"address": {
"type": "string"
}
I have removed mydata from Parse Json schema still in the output getting same input json.
I want to remove mydata element from input json and pass it further , what should be done for that in parseJson?
expected output after Parse Json
{
"data": {
"Testresults": [
{
"name": "",
"address": "",
For your requirement, I post my steps below for your reference.
In my logic app, I use the json below as the input data:
{
"data": {
"Testresults": [
{
"mydata": {
"id": "111",
"uri": "url",
"type": "demo1"
},
"name": "Michael",
"address": "abc"
},
{
"mydata": {
"id": "222",
"uri": "url",
"type": "demo2"
},
"name": "Daniel",
"address": "def"
}
]
}
}
First I create a variable to store it.
Then, parse json.
After that, we can use liquid. We need to create an integration account and link to the logic app, then upload the liquid map shown as below:
{
"data": {
"Testresults": [
{% for testresult in content.data.Testresults %}
{
"name": "{{testresult.name}}",
"address": "{{testresult.address}}"
},
{% endfor %}
]
}
}
Now, we can use "Transform JSON to JSON" action to do convert it.
Run the logic app, I get the result we expect.(without "mydata")
Hope it would be helpful to your requirement~

Read Array Value Using Dataweave in Mule

I am trying to use dataweave in Mule to read specific data values from an incoming payload. My sample payload looks like below:
{
"source": [
{
"uri": "entities/1R6xV",
"createdBy": "API_USER",
"createdTime": 1562504739146,
"attributes": {
"label": "000000000002659654",
"value": {
"Name": [
{
}
],
"Id": [
{
}
],
"Number": [
{
"type": "config/Types/Number/attributes/Number",
"ov": true,
"value": "000000000002659654",
"uri": "entities/1R6xV/attributes/Num/1ZtyT/Number/60pvN6"
}
]
}
}
}
]
}
If I need to read the "label", I can achieve that by
label: payload.source.attributes.label
Similarly, how can I read the "value" under attributes > Number. It doesn't work by:
Value: payload.source.attributes.Number.value
I am new to Dataweave. Please advise.
The problem is that the dot selector (.) works on object and on array of objects. When it is applied to an array it will apply the dot selector to all the elements of the array that are of type object and return that result.
Lets go part by part
payload.source
Returns
[
{
"uri": "entities/1R6xV",
"createdBy": "API_USER",
"createdTime": 1562504739146,
"attributes": {
"label": "000000000002659654",
"value": {
"Name": [
{
}
],
"Id": [
{
}
],
"Number": [
{
"type": "config/Types/Number/attributes/Number",
"ov": true,
"value": "000000000002659654",
"uri": "entities/1R6xV/attributes/Num/1ZtyT/Number/60pvN6"
}
]
}
}
}
]
So far so good as payload is an Object it returns the value of source that is an array
payload.source.attributes
Returns
[
{
"label": "000000000002659654",
"value": {
"Name": [
{
}
],
"Id": [
{
}
],
"Number": [
{
"type": "config/Types/Number/attributes/Number",
"ov": true,
"value": "000000000002659654",
"uri": "entities/1R6xV/attributes/Num/1ZtyT/Number/60pvN6"
}
]
}
}
]
Works ok because the result of payload.source was ended an Array of object so it will do that selection over those objects.
Now when you execute
payload.source.attributes.value.Number
It returns
[
[
{
"type": "config/Types/Number/attributes/Number",
"ov": true,
"value": "000000000002659654",
"uri": "entities/1R6xV/attributes/Num/1ZtyT/Number/60pvN6"
}
]
]
That is an array of arrays and here is where it is broken.
My Solution
You have two alternatives here
Use flatten function
flatten(payload.source.attributes.value.Number).value
Use descendant selector
payload.source.attributes.value.Number..value
Since Number is an array, you need to specify the index you want. In this case, the zeroth element:
Value: payload.source[0].attributes.value.Number[0].value
If you have multiple numbers, it would look something like this:
%dw 1.0
%output application/json
---
values: payload.source[0].attributes.value.Number map {
value: $.value
}

How to display the position within an array with Cosmos DB SQL

I have a problem attempting to select from a document array in Cosmos-db. (SQL-api)
I am able to select the values from the array however I would like to be able to display each of the values position within the array also.
Sample JSON document:
{
"Type": "SampleJSONMessage",
"Version": "1",
"Reference": "Test",
"DateTime": "2019-03-29T15:16:11.503Z",
"Configuration": {
"MessageType": "1",
"MessageConfig": "100",
"Source": [
{
"Source": "Stream1"
},
{
"Source": "Stream2"
},
{
"Source": "Stream3"
},
{
"Source": "Stream4"
}
]
}
}
I execute this:
select c.Configuration.Source from c
which returns this:
[
{
"Source": "Stream1"
},
{
"Source": "Stream2"
},
{
"Source": "Stream3"
},
{
"Source": "Stream4"
}
]
This is what I would like to display:
[
{
"Source": "Stream1" ,
"Position": "1"
},
{
"Source": "Stream2",
"Position": "2"
},
{
"Source": "Stream3",
"Position": "3"
},
{
"Source": "Stream4",
"Position": "4"
}
]
Any help appreciated!
While a specific index is stored inside CosmosDB for each array element, the SQL API doesn't currently have a method for accessing it directly. A user defined function will work though.
Here is the UDF I added to my collection:
function ADD_INDEX(array){
array.forEach(function(item, index){item.Position = index.toString()});
return array;
}
And the modified query to use this to get the output you want:
select udf.ADD_INDEX(c.Configuration.Source) AS Source from c

Correct way to loop through an JSON object [duplicate]

This question already has answers here:
Unable to iterate through JSON array
(3 answers)
Closed 6 years ago.
Since there seems nobody is able to find a solution for my problem, I would like to ask my question in a different way:
What should be the correct way to loop through the games section of the following object:
[
{
"_id": "5710b0ddab8b724011705037",
"username": "test",
"name": "testuser",
"__v": 0,
"library": {
"games": [
{
"platform": [
"17",
"94"
],
"name": "Simcity",
"id": "37620"
},
{
"platform": [
"146",
"20"
],
"name": "destiny",
"id": "36067"
}
],
"platforms": [
{
"name": "Xbox360",
"id": "20"
},
{
"name": "PC",
"id": "94"
}
]
}
}
]
This object is fetched out through mongoose out of a MongoDB, all happens in the API section of my NodeJS application:
.get('/test', function(req, res){
User.findOne({"username": req.decoded.username}, function(err, user){
// trying to loop here
});
})
I have tried everything I find, but I cannot get it to work, so I wonder what ways you use to do this, without cluttering your vision with my (maybe wrong) ways and errors...
Use for...in to loop through Javascript/JSON objects
for (variable in object) {...
}
for...in documentation
Use forEach to loop through Javascript/JSON arrays
arr.forEach(callback[, thisArg])
forEach documentation
Updated Answer:
Your edit markedly changes the structure of the data compared to your original question.
Now, you have an array containing one entry, which has library, which has games, so you reference it (assuming user points to the whole thing) as user[0].library.games. E.g.:
user[0].library.games.forEach(function(entry) {
// Use `entry` here
});
var user = [{
"_id": "5710b0ddab8b724011705037",
"username": "test",
"name": "testuser",
"__v": 0,
"library": {
"games": [{
"platform": [
"17",
"94"
],
"name": "Simcity",
"id": "37620"
}, {
"platform": [
"146",
"20"
],
"name": "destiny",
"id": "36067"
}],
"platforms": [{
"name": "Xbox360",
"id": "20"
}, {
"name": "PC",
"id": "94"
}]
}
}];
user[0].library.games.forEach(function(entry) {
log(entry.name);
});
function log(msg) {
var p = document.createElement('p');
p.appendChild(document.createTextNode(msg));
document.body.appendChild(p);
}
Original Answer:
games is an array, assuming you have o referencing that object, you can reference it from o.user.library.games.
There are lots of ways to loop over arrays (see this answer for a list); one of them is forEach:
o.user.library.games.forEach(function(entry) {
// Use `entry` here, e.g. `entry.name`, `entry.id`, etc.
});
E.g.:
var o = {
"user": {
"name": "testuser",
"library": {
"platforms": [{
"id": "20",
"name": "Xbox360"
}, {
"id": "94",
"name": "PC"
}],
"games": [{
"id": "37620",
"name": "Simcity",
"platform": [
"17",
"94"
]
}, {
"id": "36067",
"name": "destiny",
"platform": [
"146",
"Xbox360"
]
}]
}
}
};
o.user.library.games.forEach(function(entry) {
log(entry.name);
});
function log(msg) {
var p = document.createElement('p');
p.appendChild(document.createTextNode(msg));
document.body.appendChild(p);
}
From your comment below, it sounds like the structure may not be quite as you quoted it in the question. You can use node-inspector to debug your NodeJS code, set a breakpoint at the beginning of where you want to loop, and inspect the variable you have referring to the object. That will show you its structure. It's very easy to install (npm install -g node-inspector) and use (node-debug your-main-file.js).