I need to send a response from a sinatra server with multiple json object.
I have an array of hashes similar to these:
{:a=>5, :school=>"some school"} && {:id=>5, :name=>"michael"}
I would like to append a key to each one say 'school' and 'student' then send that back to the browser in one request like:
[schools:[{werererererwre},{werwrwerwewe}],
student:[{student1}, {student2}]
that's probably not fully formatted json but you understand what I'm trying to do, so then on the frontend I can just go
data.schools
to get an array of the schools
data:{
schools:{
school:{[ ], []}
student: {[], [] }
}
}
Try something like this
Figured it out, here's the spill.
hash = {}
hash[:schools] = {schools hash object}
hash[:students] = {student hash}
hash.to_json
and BOOMSHAKALAKA, DONE!
Related
I am making a network request from which I am getting a bunch of users, I am also given a emailDetails object that holds the userId property as well. I am trying to iterate over the users coming from the network request to match up all of the userIds from the emailDetails
I am not sure how to iterate, I know enumerated exists in RxSwift.
self.emailRecipients = networkRequestToGetUser
.asObservable()
.map { users in users.filter {$0.userId ==
emailDetails.userIds }.first }
.map {correctUsers in return correctUsers?.email}
.unwrap()
Error I'm getting: Binary operator '==' cannot be applied to operands of type 'String' and '[String]'
as far as I understand your code snippet, your issue is not actually related to RxSwift. Apparently emailDetails.userIds is an Array of Strings [String]. You could check if the Array contains the userId using this as you mapping instead:
.map { users in users.filter { emailDetails.userIds.contains($0.userId) }.first }
to get the first match. If you want all of them in an Array, just drop the .first and map to the email field:
self.emailRecipients = networkRequestToGetUser
.asObservable()
.map { users in
users.filter {
emailDetails.userIds.contains($0.userId)
}.map { $0.email }
}
to get a Observable of an Array of email addresses. To get the actual adresses, don't forget to subscribe() to that emailRecipients-Observable.
I am trying to use a Laravel collection to return a groupBy as an array. However, it always seems to be returned as an object no matter what. I have tried to do $posts->groupBy('category')->toArray() but this seems to still return as an object. I have also tried $posts->groupBy('category')->all() and still it is returning as an object.
I don't know if this is something to do with Laravel returning methods within the routes, but I need this to return as an array.
Here is the code:
public function getFeatures($id)
{
return Feature::query()->get()->groupBy('category')->toArray();
}
The actual code is working fine and I'm getting results back but it just doesn't seem to be converting to an array. Thanks.
When doing a query to get (possibly) several items using Eloquent, Laravel will always return an instance of the Collection class that contains all the model objects. If you need them converted to array to use them in a view you could compact the elements. compact will make an associative array of the elements of the collection:
public function getFeatures($id)
{
$features = Feature::all();
return view('my_cool_view', compact($features));
}
On the other hand, if you need them converted to array to return them through an API, Laravel convert the response to JSON by default:
public function getFeatures($id)
{
return Feature::all();
}
Now, if you somehow need the collection converted to an array, just use toArray() like you indicated:
public function getFeatures($id)
{
$collection_of_features = Feature::all();
$array_of_features = $collection_of_features->toArray();
// use it for wherever you want.
}
By reading your comment on other answer, I realized what you mean.
Hi #HCK, thanks for the answer. The ->toArray() method doesn't seem to work and still returns it like { "category_1": [], "category_2": [] } whereas I need it to do ["category_1": [], "category_2": []]
First, this answer is based on a guess that you are doing something like this on your controller (you didn't posted the controller code):
return reponse()->json($theResponseFromGetFeaturesMethod);
Since inside php the $theResponseFromGetFeaturesMethod variable contains an dictionary array (something like ["key"=>"value]), when you convert it to a JSON, you will notice that this "conversion" happens.
This happens because Javascript arrays (and JSON) doesn't support dictionary arrays. See this sample on javascript console:
> var a = [];
undefined
> a['key'] = "value"
"value"
> a
> key: "value"
length: 0
__proto__: Array(0)
Note that the a still have a length of zero, but it now have an key property.
This happens because almost everything on javascript is actually an object. So the array is a special kind of object that have push, pop and many other array methods. Doing array[] = 'somevalue' is actually a shortcut to array.push('somevalue').
So, the behavior that you are observing is right, the toArray() method work as expected, and the JSON conversion too.
Another weird behavior is when you try to convert this PHP array to an JSON:
[
0 => 'a'
1 => 'b'
9 => 'c'
]
You will note that in this case, PHP will convert this array to an object too. The result in JSON will be:
{
"0": "a",
"1": "b",
"2": "c"
}
This is also the expected behavior, since the JSON syntax doesn't support defining the index for a value.
Can someone please help me, how to execute bulk insert with header "Content-Type: application/x-ndjson" in elastic4s ? I have tried this
client.execute {
bulk(
indexInto("cars" / "car").source(getCarsFromJson)
).refresh(RefreshPolicy.WaitFor)
}.await
It works for one element in json, but when i add another element to json, no element are added to elastic.
Are you sure you are using the right syntax? Shouldn't it say
"cars/car"
Instead of
"cars" / "car"
The source method on indexInto will not support multiple json objects, because you're trying to put multiple documents inside a single document insert.
Instead, you will need to take your json, parse it into objects, and iterate over them adding an insert document for each one.
Something like the following:
def getCarsFromJson: Seq[String] = /// must return a sequence of json strings
val inserts = getCarsFromJson.map { car => indexInto("cars" /"car").source(car) }
client.execute {
bulk(inserts:_*).refresh(RefreshPolicy.WaitFor)
}
I save a hash into MongoDB using the Mongo gem. I then get a BSON::Document back when I query the database in Ruby.
How do I convert the BSON::Document back to the original hash?
doc = { name: 'Steve', hobbies: [ 'hiking', 'tennis', 'fly fishing' ]
}
result = collection.insert_one(doc)
steve = collection.find( { name: 'Steve' } ).first
returns:
{"_id"=>BSON::ObjectId('5baf68cd65992f3734f396ab'), "name"=>"Steve",
"hobbies"=>["hiking", "tennis", "fly fishing"]}
As per the details mentioned in the post it seems like you want to convert BSON db object to json(Hash) object.
BSON contains JSON module which provides the below mentioned method to convert object to json
to_json
https://www.rubydoc.info/github/mongodb/bson-ruby/BSON/JSON
Not sure of the below mentioned method, as I have only used it in ActiveRecord object, try if it works
result.as_json(only: ["name_of_the_column_you_want"])
I use ruby-2.3 and oci-8 gem. I want to make the select query:
stm = "select * from DATASERVICEUSERS t where boss<>100 and loginad is not null"
res = CONN.exec(stm).fetch_hash do |row|
#do something with row
end
CONN.logoff
How can I query the result of the whole to put for example in an array or hash, instead of cycle pass through each record? I need just a collection of elements of the result of this request.
Oci-8 doesn't provice that. The .exec method produces a cursor that you you need to process like your code demonstrates. You can fill up an array with an array of fields or a hash.
Here an example for an array
records = []
conn.exec(sql) { |record| records << record}
# records: [["xxxx", "xxxx"], ["yyyy", "yyyy"], ..]
I know this is quite an old question but I've come across this problem. I'm not as well versed in ruby but oci8 2.2.7 actually provides fetch_hash
https://www.rubydoc.info/gems/ruby-oci8/OCI8/Cursor#fetch_hash-instance_method
here's an example from my use case:
records = []
dataCursor = #odb.exec(queryUUNRData)
while((data = dataCursor.fetch_hash) != nil)
records.push data
end
dataCursor.close
the resulting dataset already includes the column names as hash key