I am trying to convert my JSON result to an array to bind it to my Kendo controls.
The JSON result that I am getting is as follows.
"Issues": [
{
"Id": null,
"Key": null,
"Values": [
{
"Key": "Display Name",
"Value": "Rya"
},
{
"Key": "UserName",
"Value": "RH"
},
{
"Key": "Count",
"Value": "350"
}
]
},
{
"Id": null,
"Key": null,
"Values": [
{
"Key": "Display Name",
"Value": "Mike"
},
{
"Key": "UserName",
"Value": "ML"
},
{
"Key": "Count",
"Value": "90"
}
]
}
]
The array that I needed to bind it to the Kendo control is as below.
{ "Display Name": 'Rya', "UserName" : "RH", value: 350 },
{ "Display Name": 'Mike', "UserName" : "ML", value: 90 }
i)I dont want to hardcode the strings "Display Name", "User Name", "RH". I tried v.Values[0].Key: v.Values[0].Value, but it didn't work.
ii) Also I will not know how many "key, value" pairs will be present, so I need to loop through the Values and generate the array instead of fixed
category: v.Values[0].Value,
UserName: v.Values[1].Value,
value: v.Values[2].Value,
.
.
.
score: v.values[n].value
If you're using ES6, you don't really need lodash in this case:
var r = json.Issues.map(v => ({
category: v.Values[0].Value,
value: v.Values[2].Value,
}));
http://codepen.io/cjke/pen/RprJdG?editors=0010
If want to use lodash or not-ES6, then:
var r = _.map(json.Issues, function(v) {
return {
category: v.Values[0].Value,
value: v.Values[2].Value,
}
});
Related
I'm looking to go from a JSON structure that looks something like this:
{
"id": "955559665",
"timestamp": "2022-04-21 00:00:19",
"user_agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_6) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/14.0 Safari/605.1.15",
"remote_addr": "123.456.789.012",
"read": "0",
"data": {
"80928111": {
"field": "80928111",
"value": "Z01234567",
"flat_value": "Z01234567",
"label": "ID",
"type": "text"
},
"90924321": {
"field": "90924321",
"value": {
"first": "Jane",
"last": "Doe"
},
"flat_value": "first = Jane\nlast = Doe",
"label": "Name",
"type": "name"
},
"88888770": {
"field": "88888770",
"value": "jdoe001#gmail.com",
"flat_value": "jdoe001#gmail.com",
"label": "Email",
"type": "email"
},
"12345678": {
"field": "12345678",
"value": "https://www.google.com/subdomain/attachment/file.txt",
"flat_value": "https://www.google.com/subdomain/attachment/file.txt",
"label": "Choose File",
"type": "file"
}
}
}
Ultimately to something like this:
{
"name_val":"Name: first = Jane\nlast = Doe\nEmail: jdoe001#gmail.com\n",
"file": {
"id": "12345678C",
"name": "file.txt"
}
}
In the original JSON, the 'data' object represents a form submission. Each sub object represents a field on the submitted form. The only distinction I'm interested in is the 'type' of field identified as 'file'.
Every response that is not of 'file' type, I want to concatenate into one large String value that looks like: 'label1: flat_value1\nlabel2: flat_value2...'
Note, the number of actual fields is variable.
Then I need a second object to show the field of type 'file', by identifying the 'field' id, and the name of the file.
I've gotten pieces of this to work. For example, using pluck and filter, I've been able to separate the types of fields.
Something like this:
%dw 2.0
output application/json
---
[
"fields": payload.data pluck(
{
"field": $."label",
"value": $."flat_value",
"type": $."type"
}
) filter ($."type" != "file") default "",
"files": payload.data pluck(
{
"type": $."type",
"fieldId": $."field"
}
) filter ($."type" == "file") default ""
]
Gives me:
[
{
"fields": [
{
"field": "ID",
"value": "Z01234567",
"type": "text"
},
{
"field": "Name",
"value": "first = Jane\nlast = Doe",
"type": "name"
},
{
"field": "Email",
"value": "jdoe001#gmail.com",
"type": "email"
}
]
},
{
"files": [
{
"type": "file",
"fieldId": "12345678"
}
]
}
]
And playing around with a modified JSON input, I was able to easily see concatenation similar to how I want to see it, but not quite there:
%dw 2.0
output application/json
var inputJson = [
{
"field": "ID",
"value": "Z01234567",
"type": "text"
},
{
"field": "Name",
"value": "first = Jane\nlast = Doe",
"type": "name"
}
]
---
inputJson map ((value, index) -> value.field ++ ': ' ++ value.value)
Gives me:
[
"ID: Z01234567",
"Name: first = Jane\nlast = Doe"
]
But I can't seem to put it all together and go from Beginning to End.
There are several ways to implement this. I recommend to try to encapsulate the parts that you get working and use them as building blocks.
%dw 2.0
output application/json
fun fields(x) = x.data pluck(
{
"field": $."label",
"value": $."flat_value",
"type": $."type"
}
) filter ($."type" != "file") default ""
fun files(x) = x.data pluck(
{
"type": $."type",
"fieldId": $."field"
}
) filter ($."type" == "file") default ""
---
{
name_val: fields(payload) reduce ((item,acc="") -> acc ++ item.field ++ ': ' ++ item.value ++ "\n"),
files: files(payload)[0]
}
Output:
{
"name_val": "ID: Z01234567\nName: first = Jane\nlast = Doe\nEmail: jdoe001#gmail.com\n",
"files": {
"type": "file",
"fieldId": "12345678"
}
}
I have an array of json objects like this
[
{
"events": [
{
"type": "message",
"attributes": [
{
"key": "action",
"value": "withdraw_reward"
},
{
"key": "sender",
"value": "bob"
},
{
"key": "module",
"value": "distribution"
},
{
"key": "sender",
"value": "bob"
}
]
},
{
"type": "credit",
"attributes": [
{
"key": "recipient",
"value": "ross"
},
{
"key": "sender",
"value": "bob"
},
{
"key": "amount",
"value": "100"
}
]
},
{
"type": "rewards",
"attributes": [
{
"key": "amount",
"value": "100"
},
{
"key": "validator",
"value": "sarah"
}
]
}
]
},
{
"events": [
{
"type": "message",
"attributes": [
{
"key": "action",
"value": "withdraw_reward"
},
{
"key": "sender",
"value": "bob"
},
{
"key": "module",
"value": "distribution"
},
{
"key": "sender",
"value": "bob"
}
]
},
{
"type": "credit",
"attributes": [
{
"key": "recipient",
"value": "ross"
},
{
"key": "sender",
"value": "bob"
},
{
"key": "amount",
"value": "100"
}
]
},
{
"type": "rewards",
"attributes": [
{
"key": "amount",
"value": "200"
},
{
"key": "validator",
"value": "Ryan"
}
]
}
]
}
]
How to traverse through the types, check if it's type equals to rewards and then go through the attributes and verify if the validator equals to sarah and fetch the value of the key amount? Pretty new to scala and play framework. Any help would be great. Thanks
You could parse your JSON into a structure of case classes for easier handling and then extract the wanted field like so:
val json =
"""[
{"events":[
{
"type":"message","attributes":[
{"key":"action","value":"withdraw_reward"},
{"key":"sender","value":"bob"},
{"key":"module","value":"distribution"},
{"key":"sender","value":"bob"}
]},
{
"type":"credit","attributes":[
{"key":"recipient","value":"ross"},
{"key":"sender","value":"bob"},
{"key":"amount","value":"100"}
]},
{
"type":"rewards","attributes":[
{"key":"amount","value":"100"},
{"key":"validator","value":"sara"}
]}
]
},
{"events":[
{
"type":"message","attributes":[
{"key":"action","value":"withdraw_reward"},
{"key":"sender","value":"bob"},
{"key":"module","value":"distribution"},
{"key":"sender","value":"bob"}
]},
{
"type":"credit","attributes":[
{"key":"recipient","value":"ross"},
{"key":"sender","value":"bob"},
{"key":"amount","value":"100"}
]},
{
"type":"rewards","attributes":[
{"key":"amount","value":"200"},
{"key":"validator","value":"Ryan"}
]}
]
}
]
"""
case class EventWrapper(events: Seq[Event])
case class KeyValue(key: String, value: String)
case class Event(`type`: String, attributes: Seq[KeyValue])
import play.api.libs.json._
implicit val kvReads: Reads[KeyValue] = Json.reads[KeyValue]
implicit val eventReads: Reads[Event] = Json.reads[Event]
implicit val eventWrapperReads: Reads[EventWrapper] = Json.reads[EventWrapper]
val rewardAmountsValidatedBySara = Json
.parse(json)
.as[Seq[EventWrapper]]
.flatMap {
_.events.collect {
case Event(t, attributes) if t == "rewards" && attributes.contains(KeyValue("validator", "sara")) =>
attributes.collect {
case KeyValue("amount", value) => value
}
}.flatten
}
val amount = rewardAmountsValidatedBySara.head
For your example, rewardAmountsValidatedBySara would yield a List of Strings containing only the String "100". Which you could retrieve (potentially unsafe) with .head as shown above.
Normally you would not do this, as it could throw an exception on an empty List, so it would be better to use .headOption which returns an Option which you can then handle safely.
Note that the implicit Reads are Macros, which automatically translate into Code, that instructs the Play Json Framework how to read the JsValue into the defined case classes, see the documentation for more info.
I have a an object. I am able to sort the items by using lodash's _.orderBy().
However, in one of the scenario I have to sort by subject, which is an array of objects. Items inside the subject array are already sorted based on the name.
As subject is an array of the objects, I need to consider the first item for sorting.
[
{
"id": "1",
"name": "peter",
"subject": [
{
"id": "1",
"name": "maths"
},
{
"id": "2",
"name": "social"
}
]
},
{
"id": "2",
"name": "david",
"subject": [
{
"id": "2",
"name": "physics"
},
{
"id": "3",
"name": "science"
}
]
},
{
"id": "3",
"name": "Justin",
"subject": [
]
}
]
You can use _.get() to extract the name (or id) of the 1st item in subjects. If no item exists, _.get() will return undefined, which can be replaced with a default value. In this case, we don't want to use an empty string as a default value, since the order would change. Instead I'm checking if the value is a string, if it is I use lower case on it, if not I return it as is.
const arr = [{"id":"1","name":"peter","subject":[{"id":"1","name":"maths"},{"id":"2","name":"social"}]},{"id":"2","name":"david","subject":[{"id":"2","name":"physics"},{"id":"3","name":"science"}]},{"id":"3","name":"Justin","subject":[]}]
const result = _.orderBy(arr, o => {
const name = _.get(o, 'subject[0].name')
return _.isString(name) ? name.toLowerCase() : name
})
console.log(result)
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.js"></script>
Use _.sortBy with a comparison/sorting function argument. Your function itself can look into the receiving arguments subject key (I think its the subject you want to compare?)
Since you have the question also tagged with ES6 here is an JS only solution via Array.sort:
let arr = [ { "id": "1", "name": "peter", "subject": [ { "id": "1", "name": "maths" }, { "id": "2", "name": "social" } ] }, { "id": "2", "name": "david", "subject": [ { "id": "2", "name": "physics" }, { "id": "3", "name": "science" } ] }, { "id": "3", "name": "Justin", "subject": [] }, ]
const result = arr.sort((a,b) =>
a.subject.length && b.subject.length
? a.subject[0].name.localeCompare(b.subject[0].name)
: a.subject.length ? -1 : 1)
console.log(result)
My Json result from the API is as below
Json result:
"Issues": [{
"Id": null,
"Key": null,
"Values": [{
"Key": "Display Name",
"Value": "Rya"
},
{
"Key": "UserName",
"Value": "RH"
},
{
"Key": "Count",
"Value": "350"
}
]
},
{
"Id": null,
"Key": null,
"Values": [{
"Key": "Display Name",
"Value": "Mike"
},
{
"Key": "UserName",
"Value": "ML"
},
{
"Key": "Count",
"Value": "90"
}
]
}
]
I did a mapping by doing as below-
.Issues.map(o =>
o.Values.reduce((acc, {
Key,
Value
}) =>
(acc[Key] = Value, acc), {}));
The result of the mapping is as below-
{ "Display Name": 'Rya', "UserName" : "RH", value: 350 },
{ "Display Name": 'Mike', "UserName" : "ML", value: 90 }
Desired Result:
{ "Display Name": 'Rya', "UserName" : "RH" },
{ "Display Name": 'Mike', "UserName" : "ML"}
In my requirement, I want to ignore the last element as shown in the desired result.
The easiest solution is a combination of map, slice and reduce:
json.Issues.map(b =>
b.Values.slice(0, -1).reduce((c,d) => {
c[d.Key] = d.Value;
return c;
}, {}));
Demo:
let j = {
"Issues": [{
"Id": null,
"Key": null,
"Values": [{
"Key": "Display Name",
"Value": "Rya"
},
{
"Key": "UserName",
"Value": "RH"
},
{
"Key": "Count",
"Value": "350"
}
]
},
{
"Id": null,
"Key": null,
"Values": [{
"Key": "Display Name",
"Value": "Mike"
},
{
"Key": "UserName",
"Value": "ML"
},
{
"Key": "Count",
"Value": "90"
}
]
}
]
};
let r = j.Issues.map(b =>
b.Values.slice(0, -1).reduce((c, d) => {
c[d.Key] = d.Value;
return c;
}, {}));
console.log(r);
One solution is to add a filter before the reduce to filter out objects with the unwanted Count property.
.Issues.map(o =>
o.Values
.filter(({ Key }) => Key !== 'Count')
.reduce((acc, {
Key,
Value
}) =>
(acc[Key] = Value, acc), {}));
You could also do this filtering inline during the reduction by not adding objects when Key === 'Count'.
Note: There is no such thing as the last property in a JS object. It is a collection of properties whose actual order is implementation dependent and unreliable. For example, printing your object in different browsers and platforms could give any order whatsoever, nothing guarantees that consistency.
To remove the last element regardless of how many items in the array I would favor something like this:
let result = data.Issues.map(issue => {
let temp = issue.Values;
temp.splice(-1);
return temp.reduce((acc, {Key, Value}) => (acc[Key] = Value, acc), {});
});
Here's a fiddle
.Issues.map(o => o.Values.reduce((acc, {Key, Value}) => (Key !== 'Count') ? (acc[Key] = Value, acc) : acc, {}));
full code:
const j = {"Issues": [
{
"Id": null,
"Key": null,
"Values": [
{
"Key": "Display Name",
"Value": "Rya"
},
{
"Key": "UserName",
"Value": "RH"
},
{
"Key": "Count",
"Value": "350"
}
]
},
{
"Id": null,
"Key": null,
"Values": [
{
"Key": "Display Name",
"Value": "Mike"
},
{
"Key": "UserName",
"Value": "ML"
},
{
"Key": "Count",
"Value": "90"
}
]
}
]
}
const r = j.Issues.map(o => o.Values.reduce((acc, {Key, Value}) => (Key !== 'Count') ? (acc[Key] = Value, acc) : acc, {}));
console.log(JSON.stringify(r, null, 2))
Note that in a reduce method, the function is also passed in the current index and the array reduce is being called on. So if you want to ignore the last element of the array, you can do something like:
Issues.map(o =>
o.Values.reduce((acc, {Key, Value}, idx, arry) => {
if(idx < arry.length -1)
acc[Key] = Value;
return acc;
}, {}
);
My existing array is as below:
"Issues": [{
"Id": null,
"Key": null,
"Values": [{
"Key": "Display Name",
"Value": "Rya"
}, {
"Key": "UserName",
"Value": "RH"
}, {
"Key": "Count",
"Value": "350"
}]
}, {
"Id": null,
"Key": null,
"Values": [{
"Key": "Display Name",
"Value": "Mike"
}, {
"Key": "UserName",
"Value": "ML"
}, {
"Key": "Count",
"Value": "90"
}]
}]
My desired array:
[{
name: 'Rya',
value: 350
}, {
name: 'Mike',
value: 90
}]
What I tried:
Data.Issues.map(o=> o.Values.reduce((acc, {Key, Value}) =>
(acc[Key] = Value, acc), {}));
this.donughtChartData1 = this.donughtChartData.map( ({UserName, Count}) =>
({ name: UserName, value: Count}) );
But this gives me:
[{
"name": "RHanney",
"value": "350"
}, {
"name": "MLuckenbill",
"value": "90"
}]
This has quotes and my highcharts doesn't work if there are quotes.
In the last line of your code, add a + before Count so it gets converted to a number:
// ...
({ name: UserName, value: +Count}) );
How adding one character can bring the solution :-)