How to format jbuilder value - ruby-on-rails

I got a jbuilder response like below
{
"name": "amb_devcernerpowerchart_com:patient_val2",
"value": "{\"value\"=>\"patient_value\", \"expiration\"=>31536000, \"created_datetime\"=>\"2019-12-09T12:09:59Z\"}"
}
I want to only value part of value i.e i want output like below.
{
"name": "amb_devcernerpowerchart_com:patient_val2",
"value": "value"=>"patient_value"
}
How do i get this?
Jbuilder file looks like this
json.name #component.preference_data.id
json.value #component.preference_data.value

From the question, it seems as though the data that you are receiving in the value field is a stringified JSON. You would have to parse the JSON and retrieve the required value as follows:
json.value JSON.parse(#component.preference_data.value)['value']
Basically, #component.preference_data.value returns a string, which is parsed into a JSON using JSON.parse. At the end of that, we get a hash whose 'value' field is retrieved.

Related

Extracting specific JSON data

I receive (similar to) the following JSON data:
{"accountId"=>"some-private-really-long-account-id",
"stats"=>
{"score"=>
{"globalScore"=>
[{"key"=>"lifetimeScore", "value"=>"571",
"key"=>"someOtherKeyHere", "value"=>"someValue"}]}
I am not quite sure how I would get the lifetime score. I've tried doing stuff like this:
puts data["globalScore"]["lifetimeScore"]["value"]
But that doesn't work. (data is of course the JSON data received).
I believe the problem here is that data["globalScore"]["lifetimeScore"]["value"] doesn't reference a valid "path" within the JSON. Better formatting helps to clarify this:
hash = {
"accountId" => "some-private-really-long-account-id",
"stats" => {
"score" => {
"globalScore" => [
{
"key" => "lifetimeScore",
"value" => "571",
"key" => "someOtherKeyHere",
"value" => "someValue"
}
]
}
}
}
This Ruby hash has some issues since a hash can't actually have multiple values for a given key, but that aside,
hash['stats']['score']['globalScore'][0]['value']
is a perfectly valid way to access the 'value' field.
My point is that the problem with the original question is not that hash#dig(...) should be used (as shown by #Phlip), it is that the "path" through the Hash data structure was actually invalid.
hash.dig("globalScore", "lifetimeScore", "value)
will fail just like the bracketed syntax in the original question.
Use JSON.parse(body) to convert your json to a hash. Then use hash.dig('stats', 'score', 'globalScore', 0, 'value') to run queries on that hash.

Render a sum attribute with Active Model Serializer or as JSON

The default code I have is Lab.all and it renders perfect json when I just Lab.all.to_json like so
{"id":1,"lab_id":1,"test_id":2,"price_cents":20000,"duration":null,"created_at":"2016-02-26T14:40:40.825Z","updated_at":"2016-02-26T14:40:40.825Z"}
I have the following scope:
#lab_tests = LabTest.group(:lab).sum(:price_cents) and it returns the following as json :
{"#\u003cLab:0x007f8e0a44afa8\u003e":20000}
How can I make it render json like so:
{"id":1,"lab_id":1,"test_id":2,"price_cents":20000,"duration":null,"created_at":"2016-02-26T14:40:40.825Z","updated_at":"2016-02-26T14:40:40.825Z", "price_cents":200000 }
I've tried added a .select parameter to my scope, but even that does not change anything.

Removing quotes from JSON Rails 4 and JBuilder

I'm trying to send a JSON API response from my rails app to Dasheroo which expects the following format:
{
my_statistic: { type: 'integer', value: 1, label: 'My Statistic' }
}
However it is not happy with my data structure generated by the following code:
In controller:
def count_foo_members
#foo = Foo.all.count
end
In count_foo_members.json.jbuilder:
json.foo_members do
json.type 'integer'
json.value #foo
json.label 'Foo Members'
end
If I open this route in my browser I can see the following:
{
"foo_members":{"type":"integer","value":1,"label":"Foo Members"}
}
From the results above, the only thing that I can see that could have an effect on the result is the fact that my JSON result has quotation marks around the JSON Key values.
My question thus is: How can I remove these quotation marks in Rails 4 and JBuilder?
JSON.parse(you_response) and you get standart hash.
You cannot remove the quotation marks from the keys. The responsibility is on the consumer (Dasheroo) to parse your JSON string into a JavaScript Object, which will "remove" the quotes from the keys.
Read json-object-with-or-without-quotes for further practical insight.

Iterating through JSON data from external API in Rails

I have a function return_summoner_champion_list(name) that will return the following JSON data when called
[
{
"id"=>"1",
"name"=>"A"
},
{
"id"=>"2",
"name"=>"B"
},
and so on...
]
How do I iterate through the JSON array and print out all ids?
I tried
return_summoner_champion_list(name).each do |list|
puts list["id"]
end
but it still returns the same JSON data as above without any changes.
I think you're looking for Array#collect not Array#each:
return_summoner_champion_list(name).collect{|l| l['id']}
=> [1,2, ...]
Is your method returning JSON or an Ruby array? If it is indeed returning JSON, first convert that to an array with JSON.parse(), and then work with the array that is returned.

How can I create this JSON structure with JBuilder and Rails?

TL;DR:
How can i use jbuilder to create JSON that looks like this?
[
{}, // Your new pagination state
[{}, ...] // An array of JSON objects
]
Longer version:
I am trying get pagination working with Backbone.js and backbone-pageable https://github.com/wyuenho/backbone-pageable .
Backbone-pageable requires that the JSON returned be formatted such that it's an array of two objects. The first object is a regular object containing pagination control information. The second object should be an array of your actual data formatted as Backbone would normally expect. These expectations are hard coded into backbone-pageable's parse methods (source)
It seems weird to have an array of un-like items but for this use case it seems acceptable.
For json i've used rabl in the past but for science I'm trying to use jbuilder and I've gotten this far...
JSON structure (wrong):
{
"current_page": 1,
"total_pages": 6,
...,
"entries": [
{ "id": 131 },
...
]
}
Using this code:
json.current_page #posts.current_page
...
json.entries #posts do |post|
json.extract! post, :id...
end
Closer, but still very wrong :/
Thank you
Can you try this:
json.array! [0,1] do |index|
if index == 0
json.current_page #posts.current_page
...
else
json.entries #posts do |post|
json.extract! post, :id...
end
end
end

Resources