For a list of "a","b","c" I want to iterate with its index, like the Python code. How do I do it? I hope for ES5 code.
for index,val in enumerate(["a","b","c"]): print index,val
0 a
1 b
2 c
var list = Immutable.List(['a', 'b', 'c']);
list.forEach(function(value, index){console.log(value, index)});
Just be aware that it will return the length of the list.
Related
json_data = [{'User_Info':[{'Name':'John'},{'Name':'Ashly'},
{'Name':'Herbert'}]},
{'User_Info':[{'Name':''}]},
{'User_Info':[{'Name':'Lee'},{'Name':'Patrick'},{'Name':'Herbert'}]},
{'User_Info':[{'Name':'Benjamine'}]}]
I have JSON data and the length of the data is 5. I'd like to use loops to find names from that data. I've tried the code below but didn't get the expected outputs:
names_outputs = []
for ppl in json_data:
for i in ppl['User_Info']:
names_outputs.append(i['Name'])
print(names_outputs)
>>['John','Ashly','Herbert','Lee','Patrick','Walter','Steve','Benjamine']
However, my expected outputs should be like this:
[['John','Ashly','Herbert'],[],['Lee','Patrick','Herbert'],['Walter','Steve'],['Benjamine']]
You can use a nested list comprehension for that:
>>> [[name["Name"] for name in people] for people in [d["User_Info"] for d in json_data]]
[['John', 'Ashly', 'Herbert'], [''], ['Lee', 'Patrick', 'Herbert'], ['Benjamine']]
If you want to eliminate empty strings, use filter:
>>> [filter(None, [name["Name"] for name in people]) for people in [d["User_Info"] for d in json_data]]
[['John', 'Ashly', 'Herbert'], [], ['Lee', 'Patrick', 'Herbert'], ['Benjamine']]
I want to apply SplitJson in order to split the following JSON file into 2 FlowFiles (according to hits):
{"took":0,"timed_out":false,"_shards":
{"total":5,"successful":5,"failed":0},
"hits":{"total":2,"max_score":0.0,
"hits":
[
{"_index":"my_index","_type":"my_entry","_id":"111","_score":0.0,"_source":{"ZoneId":"1","OriginId":"1"},
"fields":{"ttime":[11000]}},
{"_index":"my_index","_type":"my_entry","_id":"222","_score":0.0,"_source":{"ZoneId":"1","OriginId":"2"},
"fields":{"ttime":[5000]}}
]
}
}
Which JsonPath Expression should I use? I tried $.hits[*], but it splits the content according to the first level hits. In my case I have hits[hits[...]], but how should I specify it in the expression?
UPDATE:
I want to get two FlowFiles:
FlowFile #1: {"_index":"my_index","_type":"my_entry","_id":"111","_score":0.0,"_source":{"ZoneId":"1","OriginId":"1"},"fields":{"ttime":[11000]}}
FlowFile #2:
{"_index":"my_index","_type":"my_entry","_id":"222","_score":0.0,"_source":{"ZoneId":"1","OriginId":"2"},"fields":{"ttime":[5000]}}
var arr = $.hits.hits;
Will give you the array with 2 objects you desire.
var o1 = arr[0];
var o2 = arr[1];
Will give you 2 objects you desire.
var json1 = JSON.stringify(arr[0]);
var json2 = JSON.stringify(arr[1]);
Will give you 2 JSON files as requested.
Is this what you needed?
You can use this website for testing JSONPath Index for your case.
The right answer is $.hits.hits[*].
As mentioned DanteTheSmith, you can simply use $.hits.hits in your case. It depends on the post-processing. Both methods work fine.
I'm trying to use a PCRE regular expression to extract some JSON. I'm using a version of MariaDB which does not have JSON functions but does have REGEX functions.
My string is:
{"device_types":["smartphone"],"isps":["a","B"],"network_types":[],"countries":[],"category":["Jebb","Bush"],"carriers":[],"exclude_carriers":[]}
I want to grab the contents of category. I'd like a matching group that contains 2 items, Jebb and Bush (or however many items are in the array).
I've tried this pattern but it only matches the first occurrence: /(?<=category":\[).([^"]*).*?(?=\])/g
Does this match your needs? It should match the category array regardless of its size.
"category":(\[.*?\])
regex101 example
JSON not a regular language. Since it allows arbitrary embedding of balanced delimiters, it must be at least context-free.
For example, consider an array of arrays of arrays:
[ [ [ 1, 2], [2, 3] ] , [ [ 3, 4], [ 4, 5] ] ]
Clearly you couldn't parse that with true regular expressions.
See This Topic:
Regex for parsing single key: values out of JSON in Javascript
Maybe Helpful for you.
Using a set of non-capturing group you can extract a predefined json array
regex answer: (?:\"category\":)(?:\[)(.*)(?:\"\])
That expression extract "category":["Jebb","Bush"], so access the first group
to extract the array, sample java code:
Pattern pattern = Pattern.compile("(?:\"category\":)(?:\\[)(.*)(?:\"\\])");
String body = "{\"device_types\":[\"smartphone\"],\"isps\":[\"a\",\"B\"],\"network_types\":[],\"countries\":[],\"category\":[\"Jebb\",\"Bush\"],\"carriers\":[],\"exclude_carriers\":[]}";
Matcher matcher = pattern.matcher(body);
assertThat(matcher.find(), is(true));
String[] categories = matcher.group(1).replaceAll("\"","").split(",");
assertThat(categories.length, is(2));
assertThat(categories[0], is("Jebb"));
assertThat(categories[1], is("Bush"));
There are many ways. One sloppy way to do it is /([A-Z])\w+/g
Please try it on your console like
var data = '{"device_types":["smartphone"],"isps":["a","B"],"network_types":[],"countries":[],"category":["Jebb","Bush"],"carriers":[],"exclude_carriers":[]}',
res = [];
data.match(/([A-Z])\w+/g); // ["Jebb", "Bush"]
OK the above was pretty sloppy however a solid single regex solution to extract every single element regardless of the number, one by one and to place them in an array (res) is the following...
var rex = /[",]+(\w*)(?=[",\w]*"],"carriers)/g,
str = '{"device_types":["smartphone"],"isps":["a","B"],"network_types":[],"countries":[],"category":["Jebb","Bush","Donald","Trump"],"carriers":[],"exclude_carriers":[]}',
arr = [],
res = [];
while ((arr = rex.exec(str)) !== null) {
res.push(arr[1]); // <- ["Jebb", "Bush", "Donald", "Trump"]
}
Check it out # http://regexr.com/3d4ee
OK lets do it. I have come up with a devilish idea. If JS had look-behinds this could have been done simply by reversing the applied logic in the previous example where i had used a look-forward. Alas, there aren't... So i decided to turn the world the other way around. Check this out.
String.prototype.reverse = function(){
return this.split("").reverse().join("");
};
var rex = /[",]+(\w*)(?=[",\w]*"\[:"yrogetac)/g,
str = '{"device_types":["smartphone"],"isps":["a","B"],"network_types":[],"countries":[],"category":["Jebb","Bush","Donald","Trump"],"carriers":[],"exclude_carriers":[]}',
rev = str.reverse();
arr = [],
res = [];
while ((arr = rex.exec(rev)) !== null) {
res.push(arr[1].reverse()); // <- ["Trump", "Donald", "Bush", "Jebb"]
}
res.reverse(); // <- ["Jebb", "Bush", "Donald", "Trump"]
Just use your console to confirm.
In c++ you can do it like this
bool foundmatch = false;
try {
std::regex re("\"([a-zA-Z]+)\"*.:*.\\[[^\\]\r\n]+\\]");
foundmatch = std::regex_search(subject, re);
} catch (std::regex_error& e) {
// Syntax error in the regular expression
}
If the number of items in the array is limited (and manageable), you could define it with a finite number of optional items. Like this one with a maximum of 5 items:
"category":\["([^"]*)"(?:,"([^"]*)"(?:,"([^"]*)"(?:,"([^"]*)"(?:,"([^"]*)")?)?)?)?
regex101 example here.
Regards.
I have difficulty processing a list a Scala:
Currently I have a list of like this
(List(JString(2437), JString(2445), JString(2428), JString(321)), CompactBuffer((4,1)))
and I would like after processing, the result will look like below:
( (2437, CompactBuffer((4,1))), (2445, CompactBuffer((4,1))), (2428, CompactBuffer((4,1))), (321, CompactBuffer((4,1))) )
Can any body help me with this issue?
Thank you very much.
Try this:
val pair = (List(JString(2437), JString(2445), JString(2428), JString(321)),
CompactBuffer((4,1)))
val result = pair._1.map((_, pair._2))
First, pair._1 gets the list from the tuple. Then, map performs the function on each element of the list. The function (_, pair._2) puts the given element from the list in a new tuple together with the second part of the pair tuple.
I have two arrays, array1 and array2. I need to compare both of these arrays and I want to create a third array, array3, whereby it shows the elements that are in array2, that are not in array1.
This is what I have so far:
my_buckets = Model.select("DISTINCT bucket").where(["my_id = ?", params[:user]])
all_buckets = Model.select("DISTINCT bucket").collect { |x| x.bucket }.uniq.compact
buckets_not_in_my_buckets = Model.select("DISTINCT bucket").where(["bucket NOT IN (?)", my_buckets]).collect { |x| x.bucket }.uniq.compact
For some reason, the buckets_not_in_my_buckets is always returning an empty array ([]). Is there a better way to approach this? Any help would be appreciated.
buckets_not_in_my_buckets = all_buckets - my_buckets
I'm assuming that you have the eql? operator on your buckets object working how you'd like.
Please see the Array docs for more detail.