I have a json object "FoundAt" : [1, 3]
How do I represent the values in the array using handlebar.js?
If you are referring to iterating the array you can do so using {{each}} block, with reference to the above defined array use the following:
{{#each jsonObjectName.FoundAt}}
{{this}}
{{/each}}
OR
{{#each number in jsonObjectName.FoundAt}}
{{number}}
{{/each}}
Look for Simple Iterators in the official documentation
Related
I have an array and I want to fill it with strings taken from specific XML nodes, like in this pseudocode example:
let $array := array {}
for $child in $collection
where contains(data($child), "Hey")
do $array := array:append($array, data($child))
How would correct code look like to perform such an operation?
So if I have this XML
<root>
<child>Hey</child>
<child>Ho</child>
<child>Hey Ho</child>
</root>
I expect the array to be
array ["Hey", "Hey Ho"]
XQuery is a functional language. As such, variables cannot be reassigned once they have been declared.
The following code should do the trick:
array {
for $child in $collection
where contains(data($child/node1), "Hey")
return $child/node2
}
Please note that the native XQuery data type for values is a sequence. Depending on your use case, maybe you don’t need arrays at all.
This should be a simple thing to do in Handlebars, but I can't seem to do it.
I have two objects:
a: {
key1: "w",
key2: "x"
}
b: {
key1: "y",
key2: "z"
}
I'm trying something like this:
{{#each a}}
{{b.#key}}
{{/each}}
<!-- Should output "y z" but it doesn't! -->
What am I doing wrong here?
I am not really sure if you can use "#key" in the dot notation, because every-time you try doing the same, Handlebars compilation fails.
Moreover, b is not an object present in a. So, if you're iterating over a, you can never get keys of b.
{{#each b}}
{{#key}}
{{/each}}
This is the block of code that would iterate over "b" object, and would print all the keys present in b, meaning "y" and "z".
However, if you change your JSON to,
a: {
'kx':'x',
'ky':'y',
b:{
'by':'y',
'bz':'z'
}
}
then, you may get the keys of b, by saying,
{{#each a.b}}
{{#key}}
{{/each}}
Which would again, give you the desired result, i.e. by and bz.
Is there a way to access dictionary keys in Swift 2 using an index?
var dict = ["item1":1, "item2":2, "item3":3]
dict.keys[0]
results in the error:
15:29: note: overloads for 'subscript' exist with these partially
matching parameter lists: (Base.Index), (Range),
(Self.Index)
print("key=" + dict.keys[i])
I saw an examples from August (Swift: dictionary access via index) doing this:
dict.keys.array[0]
At least in Swift 2, there isn't an array object on dictionary keys.
In Swift 2 the equivalent of dict.keys.array would be Array(dict.keys):
let dict = ["item1":1, "item2":2, "item3":3]
let firstKey = Array(dict.keys)[0] // "item3"
Note: of course, as dictionaries are unordered collections, "first key" of the resulting array may not have a predictable value.
do not rely on order of items in a dictonary, using array directly would be better in your case, you can also handle key/value in array with making array units objects.
I'm using the latest(0.117) Presto and trying to execute CROSS JOIN UNNEST with complex JSON array like this.
[{"id": 1, "value":"xxx"}, {"id":2, "value":"yy"}, ...]
To do that, first I tried to make an ARRAY with the values of id by
SELECT CAST(JSON_EXTRACT('[{"id": 1, "value":"xxx"}, {"id":2, "value":"yy"}]', '$..id') AS ARRAY<BIGINT>)
but it doesn't work.
What is the best JSON Path to extract the values of id?
This will solve your problem. It is more generic cast to an ARRAY of json (less prone to errors given an arbitrary map structure):
select
TRANSFORM(CAST(JSON_PARSE(arr1) AS ARRAY<JSON>),
x -> JSON_EXTRACT_SCALAR(x, '$.id'))
from
(values ('[{"id": 1, "value":"xxx"}, {"id":2, "value":"yy"}]')) t(arr1)
Output in presto:
[1,2]
... I ran into a situation where a list of jsons was nested within a json. My list of jsons had an ambiguous nested map structure. The following code returns an array of values given a specific key in a list of jsons.
Extract the list using JSON EXTRACT
Cast the list as an array of jsons
Loop through the json elements in the array using the TRANSFORM function and extract the value of the key that you are interested in.
>
TRANSFORM(CAST(JSON_EXTRACT(json, '$.path.toListOfJSONs') AS ARRAY<JSON>),
x -> JSON_EXTRACT_SCALAR(x, '$.id')) as id
You can cast the JSON into an ARRAY of MAP, and use transform lambda function to extract the "id" key:
select
TRANSFORM(CAST(JSON_PARSE(arr1) AS ARRAY<MAP<VARCHAR, VARCHAR>>), entry->entry['id'])
from
(values ('[{"id": 1, "value":"xxx"}, {"id":2, "value":"yy"}]')) t(arr1)
output:
[1, 2]
Now, you can use presto-third-functions , It provide json_array_extract function, you can extract json array info like this:
select
json_array_extract_scalar(arr1, '$.book.id')
from
(values ('[{"book":{"id":"12"}}, {"book":{"id":"14"}}]')) t(arr1)
output is:
[12, 14]
I finally gave up finding a simple JSON Path to extract them.
Instead, I wrote a redundant dirty query like the following to make the task done.
SELECT
...
FROM
(
SELECT
SLICE(ARRAY[
JSON_EXTRACT(json_column, '$[0].id'),
JSON_EXTRACT(json_column, '$[1].id'),
JSON_EXTRACT(json_column, '$[2].id'),
...
], JSON_ARRAY_LENGTH(json_column)) ids
FROM
the.table
) t1
CROSS JOIN UNNEST(ids) AS t2(id)
WHERE
...
I still want to know the best practice if you know another good way to CROSS JOIN them!
var dict = ["alpha": ["a", "b", "c", "d"]]
// output : ["alpha": ["a", "b", "c", "d"]]
var alphaList = dict["alpha"]
// output : {["a", "b", "c", "d"]
alphaList?.removeAtIndex(1)
// output : {Some "b"}
alphaList
// output : {["a", "c", "d"]}
dict
// output : ["alpha": ["a", "b", "c", "d"]]
Why is 'dict' not altered? Is it because 'alphaList' is a copy of the array and not the actual array inside the dictionary? Can anyone point me where in Swift language documentation I can find this information?
What is the correct/functional way to manipulate values (of complex type) of a dictionary?
Good question yes it creates the copy of the value in your case the value is Array
var alphaList = dict["alpha"]
/* which is the copy of original array
changing it will change the local array alphaList as you can see by your output */
output : {Some "b"}
In order to get the original array directly use
dict["alpha"]?.removeAtIndex(1)
Or update it using the key
alphaList?.removeAtIndex(1)
dict["alpha"] = alphaList
Apple : Assignment and Copy Behavior for Strings, Arrays, and Dictionaries
Swift’s String, Array, and Dictionary types are implemented as structures. This means that strings, arrays, and dictionaries are copied when they are assigned to a new constant or variable, or when they are passed to a function or method.
This behavior is different from NSString, NSArray, and NSDictionary in Foundation, which are implemented as classes, not structures. NSString, NSArray, and NSDictionary instances are always assigned and passed around as a reference to an existing instance, rather than as a copy. "
Swift arrays and dictionaries are value (struct) times. There are only one reference to such instance. While NSArray and NSDictonary are class type and there could be multiple references to such instances.
The statement var alphaList = dict["alpha"] makes copy for ["a", "b", "c", "d"], so you cannot change the original array.
If you want to mutate original "alpha" you have to use dict as root variable:
dict["alpha"]?.removeAtIndex(1)
You are right, alphaList is a copy, hence any change you make on it is local and does not affect the original array. The documentation describes that in Structures and Enumerations Are Value Types.
The only way to make changes to an array after extracting it from somewhere else is by passing the array to a function by reference, using the inout parameter modifier:
func modifyAlphaList(inout alphaList: [String]?) {
alphaList?.removeAtIndex(1)
}
modifyAlphaList(&dict["alpha"])
dict // (.0 "alpha", ["a", "c", "d"])
This link should help
https://developer.apple.com/library/prerelease/mac/documentation/Swift/Conceptual/Swift_Programming_Language/ClassesAndStructures.html#//apple_ref/doc/uid/TP40014097-CH13-XID_150
Swift’s String, Array, and Dictionary types are implemented as structures. This means that strings, arrays, and dictionaries are copied when they are assigned to a new constant or variable, or when they are passed to a function or method.