I have Array[Row] called arr (I obtained it after df.collect()) that I want to pass in my JSON string as key and value pairs:
val result = """{"field1": "A", "arr": [""" + arr + """]}"""
It should be:
{"field1": "A", "arr": [
{"name":"Ford", "model": "Fiesta"},
{"name":"Ford", "model": "Mustang"},
...
]}
If I do it the way that I showed above, it will not work.
Should I iterate over this array and manually define each parameter?:
arr.get(i).get(arr.get(i).fieldIndex("field1")).toString()
You should be doing as below by using .toJSON as suggested by philantrovert in comments of the question
val result = """{"field1":"A","arr":"""+df.toJSON.collectAsList()+"""}"""
If you are using arr variable then you can do
val arr = df.toJSON.collectAsList()
val result = """{"field1":"A","arr":"""+arr+"""}"""
Related
Here's what I would like to do.
number = [ 0, 1, 2]
array0 = [ "AA", "BB"]
array1 = [ "CC", "DD"]
array2 = [ "EE", "FF"]
I want to be able to be able to reference the name of the array by doing something like this.
selectedArray = "array" + String(number[2])
then with this, I would like to be able to reference the values inside such as
print("array2:\(selectedArray[1]))
/// The answer would be --> array2:FF
Right now, I've not been able to achieve this, and I tried this but it doesn't work.
selectedArray = Array("array" + String(number[2]))
I tried googling but not knowing how to describe this, I didn't fare well in the results.
Note : The array is a list of GPS Dist / Lat / Lon (very long) and rather than have 1 very huge array, I'm thinking of splitting them out into eg: 10 diff arrays
Not sure I understand correctly what you are trying to achieve and the logic but you can create an array of arrays (lat and long). Something like this:
let number = [0,1,2] // not sure why you need this array
let array = [[ "AA", "BB"],
[ "CC", "DD"],
[ "EE", "FF"]]
let selectedNumber = number[2]
print("array\(selectedNumber):\(array[selectedNumber][1])")
However, I would advice to use this approach:
create a Model for you Coordinates
struct Coordinates {
var lat:String //this should be a Double but
//for the sake of the example I use String
var long:String //Same here
}
then in the controller add data to an array of Coordinates
let coordinate1 = Coordinates(lat: "AA", long: "BB")
let coordinate2 = Coordinates(lat: "CC", long: "DD")
let coordinate3 = Coordinates(lat: "EE", long: "FF")
let array2:[Coordinates] = [coordinate1,coordinate2,coordinate3]
let selectedNumber = number[2]
print("array\(selectedNumber):\(array2[selectedNumber].long)")
which still prints
array2:FF
I want to implement a multiple click in my Shinobi DataGrid. I have a grid which have array
( ["1", "32", and more] )
If I click the grid I put it into new Array self.arrayNr.append(currNr).
But I want to check and remove if currNr is already exist in arrayNr it is will be remove from the arrayNr.
I'm new and using Swift 3. I read some question regarding with my question like this and this but it's not working. I think the Swift 2 is simpler than Swift 3 in handling for String. Any sugesstion or answer will help for me?
You can use index(of to check if the currNrexists in your array. (The class must conform to the Equatable protocol)
var arrayNr = ["1", "32", "100"]
let currNr = "32"
// Check to remove the existing element
if let index = arrayNr.index(of: currNr) {
arrayNr.remove(at: index)
}
arrayNr.append(currNr)
Say you have an array of string, namely type [String]. Now you want to remove a string if it exists. So you simply need to filter the array by this one line of code
stringArray= stringArray.filter(){$0 != "theValueThatYouDontWant"}
For example, you have array like this and you want to remove "1"
let array = ["1", "32"]
Simply call
array = array.filter(){$0 != "1"}
Long Solution
sampleArray iterates over itself and removes the value you are looking for if it exists before exiting the loop.
var sampleArray = ["Hello", "World", "1", "Again", "5"]
let valueToCheck = "World"
for (index, value) in sampleArray.enumerated() {
if value == valueToCheck && sampleArray.contains(valueToCheck) {
sampleArray.remove(at: index)
break
}
}
print(sampleArray) // Returns ["Hello", "1", "Again", "5"]
Short Solution
sampleArray returns an array of all values that are not equal to the value you are checking.
var sampleArray = ["Hello", "World", "1", "Again", "5"]
let valueToCheck = "World"
sampleArray = sampleArray.filter { $0 != valueToCheck }
print(sampleArray) // Returns ["Hello", "1", "Again", "5"]
I have a jsonb field in PostgreSQL with the following content:
{ "object": { "urls": "A;B;C" } }
What I want to do is update the value of urls inside the object and transform the string with semicolon separated values into a JSON array. So the result should look like this:
{ "object" : { "urls": ["A", "B", "C"] } }
I found out how to get a JSON array. Using
to_json(string_to_array(replace((json->'object'->'urls')::text, '"',''), ';'));
gives me ["A", "B", "C"] (I think there should be a better way of doing it without the conversion json -> text -> array -> json. Suggestions are welcome)
But how do I update the urls field with the json array now? Probably I have to use jsonb_set?
Use jsonb and the function jsonb_set():
create table my_table(id int primary key, jdata jsonb);
insert into my_table values
(1, '{ "object": { "urls": "A;B;C" } }');
update my_table
set jdata = jsonb_set(
jdata,
array['object', 'urls'],
to_jsonb(string_to_array(replace((jdata->'object'->'urls')::text, '"',''), ';'))
)
returning *;
id | jdata
----+-------------------------------------
1 | {"object": {"urls": ["A", "B", "C"]}}
(1 row)
I have a dictionary -> var dictionary = [String : [String]]() and I want to append string values in the array of the dictionary. This is how I'm doing it
for (key, value) in dictionary {
dictionary.updateValue(value.append(nameText),forKey: "name")
}
Here, nameText is a string, I'm getting an error saying,
Cannot use mutating member on immutable value: 'value' is a 'let' constant.
What am I doing wrong? Help would be much appreciated.
Your first issue is that value is a let constant within your loop body. You must declare it as var in order to mutate it.
Your second issue is that you're trying to use value.append(nameText) as the value to set for the key. However, append() mutates the array in place, and returns Void.
Thirdly, don't use updateValue(forKey:). There's really no point. Use subscripting instead.
var dictionary = [
"a" : ["a"],
"b" : ["b", "b"],
"c" : ["c", "c", "c"],
]
let nameText = "foo"
for (key, var value) in dictionary {
value.append(nameText)
dictionary["name"] = value
}
Now, this gets your code to compile, but I'm highly skeptical this is really what you want to do. You'll be overwriting the value for the "name" key on every iteration, meaning only the last iteration's value will persist. Furthermore, because Dictionary doesn't have a defined ordering, this code has indeterminate behaviour. What are you actually trying to do?
Try this:
for (key, value) in dictionary {
dictionary.updateValue(value + [nameText], forKey: key)
}
Think about it for a second; value.append(nameText) is an action. It returns Void (the type for ... nothing!).
You want to update the value to something upon which an action has been performed.
Instead of manually making a temporary copy, modifying that, and then using it to update the value for some key, you can simply use subscripts and extensions:
What you want is:
extension Dictionary
{
public subscript(forceUnwrapping key: Key) -> Value
{
get
{
return self[key]!
}
set
{
self[key] = newValue
}
}
}
So, for a dictionary named dictionary:
for key in dictionary.keys
{
dictionary[forceUnwrapping: key].append(nameText)
}
Specifically, dictionary[forceUnwrapping: key].append(nameText).
/* example setup */
var dictionary: [String: [String]] = ["foo": [], "bar": []]
let nameText = "foobar"
/* append the value of the 'nameText' immutable to each inner array */
dictionary.keys.forEach { dictionary[$0]?.append(nameText) }
/* ok! */
print(dictionary) // ["bar": ["foobar"], "foo": ["foobar"]]
As described in the following Q&A, however
Dictionary in Swift with Mutable Array as value is performing very slow? How to optimize or construct properly?
..., it is good to be aware of the overhead of mutating "in place", especially if working performance tight applications. Taking the advice from the answer in the linked thread above, an alternative, more sensible and less copy-wasteful approach would be e.g.:
var dictionary: [String: [String]] = ["foo": [], "bar": []]
let nameText = "foobar"
dictionary.keys.forEach {
var arr = dictionary.removeValue(forKey: $0) ?? []
arr.append(nameText)
dictionary[$0] = arr
}
print(dictionary) // ["bar": ["foobar"], "foo": ["foobar"]]
I have an object like
data: Array[1];
which can be accessed like
data[0].name
data[0].place
I am trying to convert this to JSON using like
var arr = JSON.stringify(data);
which returns
var arr = [{"name": "blah", "place": "ca"}]
But Im confused how to use this arr now its stringified ? How do I access for example the "name" value ? I tried arr.name but that doesn't seem to work ?
The array is
arr == [{"name": "blah", "place": "ca"}];
That object is the first item in the array
arr[0] == {"name": "blah", "place": "ca"}
and its properties...
arr[0].name == "blah"
your "name" is inside the hash/associative array which is inside an array
so u need to grab hash/associative array first, using
arr[0]
and then u can access your attributes.