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.
Related
I'm attempting to access an object in an Json response, but not sure how. How can I access ID 11 using rest-assured, where ObjID1 and ObjID2 are unique UUID's?
"ObjID1": [
{
"ID": "11",
"NAME": "XYZ",
"GENDER": "M"
}
]
"ObjID2": [
{
"ID": "12",
"NAME": "Z",
"GENDER": "F"
}
]
To assert element's value you can use
then().body("ObjID1.ID[0]", equalTo("11"))
Indexing ID field with [0] allows you to get the ID of first JSON Object in the Array.
If you want to get this value for further processing then you can extract it like this:
JsonPath path = JsonPath.from("json file or json String");
List<HashMap<String, Object>> listOfJsonObjects = path.get("ObjID1");
We parsed the JSON and by using the path.get method we save Array of JSON Objects inside List of HashMaps. Each element in the list is the JSON Object.
In order to access first JSON Object you can use
HashMap<String, Object> jsonObject = listOfJsonObjects.get(0);
and then, using classic HashMap methods you can get specific element in the JSON Object like this:
jsonObject.get("ID");
The above will return "11"
Note that you will have to make a cast to String to get the value. Values in the HashMap are objects because JSON Objects in the array may contain nested Arrays or Objects.
String firstId = (String) jsonObject.get("ID");
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+"""}"""
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 this collection :
{
username : "user1",
arr : [
{
name : "test1",
times : 0
},
{
name : "test2",
times : 5
}
]
}
I have an array with some object. This objects have a name and the value times. Now I want to add new objects, if my array doesn't contain them. Example:
I have this two objects with the name "test1" and "test2" already in the collection. I want now to insert the objects "test2", "test3" and "test4". It should only add the object "test3" and "test4" to the array and not "test2" again. The value times doesn't do anything in this case, they should just have the value 0 when it gets insert.
Is there a way to do this with one query?
If you can insert test1, test2,... one by one, then you can do something like this.
db.collection.update(
{username : "user1", 'arr.name': {$ne: 'test2'}},
{$push: {
arr: {'name': 'test2', 'times': 0}
}
})
The $ne condition will prevent the update if the name is already present in arr.
You can now use the addToSet operator that is built just for that: adds a value to an array if it does not exist.
Documentation: https://docs.mongodb.com/manual/reference/operator/update/addToSet/
MongoDB seems to interpret $set paths with numerical components as object keys rather than array indexes if the field has not already been created as an array.
> db.test.insert({_id: "one"});
> db.test.update({_id: "one"}, {$set: {"array.0.value": "cheese"}});
> db.find({_id: "one"})
{ "_id": "one", "array": { "0" : { "value" : "cheese" } }
I expected to get "array": [{"value": "cheese"}], but instead it was initialized as an object with a key with the string "0".
I could get an array by initializing the whole array, like so:
> db.test.update({_id: "one"}, {$set: {"array": [{"value": "cheese"}]}});
... but this would clobber any existing properties and other array elements that might have been previously set.
Is there any way to convince $set that I want "array" to be an array type, with the following constraints:
I want to execute this in a single query, without looking up the record first.
I want to preserve any existing array entries and object values
In short, I want the behavior of $set: {"array.0.value": ... } if "array" had already been initialized as an array, without knowing whether or not it has. Is this possible?
I am not sure if this is possible without lookup. Perhaps you can change schema design, and try something like this:
db.test.insert({_id: "one"});
db.test.update({_id: "one"}, {$addToSet: {array: { $each:['cheese', 'ham'] }}});
db.test.findOne({_id:'one'});
// { "_id" : "one", "array" : [ "cheese", "ham" ] }
Handling array elements (sub-documents in array) in MongoDb is pain. https://jira.mongodb.org/browse/SERVER-1243