My JSON API is like below,
{ "schedule_id": "1",
"latitude" : 17.4327,
"longitude" : 78.4302,
"device_id": "123test",
"audit_compliances":[
{
"value": "Yes",
"score": 10,
"remarks": "some remarks",
"private_remarks": "some remarks",
"check_point_id": 1,
"audit_compliance_documents":[{
"score": 10,
"remarks": "some remarks",
}]
}]
i have a relations for that DB i want to save all this records at once so i want to initialize the object with details and build inner objects along with that. Started building like this but how can i build inner build for documents.
submission = Submission.new(audit_schedule_id: params[:schedule_id],
latitude: params[:latitude], longitude: params[:longitude],
device_id: params[:device_id])
params[:audit_compliances].each do |audit_compliance|
submission.audit_compliances.build(
value: audit_compliance[:value],
score: audit_compliance[:score],
remarks: audit_compliance[:remarks],
private_remarks: audit_compliance[:private_remarks],
check_point_id: audit_compliance[:check_point_id])
end
pass your json param in submission params directly
like this
params[:submission] = json_params;
Submission.create(params[:submission]);
It will create both if your mapping is correct........
Related
Please tell me, if there are any errors here and how to make the code more clean.
There is a space "company". Inside it's a string "type" and "information" map. Inside this map is a "job" object and an array of "users" objects. The "users" array consists of 2 objects. Each object has 4 fields.
I need to add a new field:
status = "UPDATED"
inside each object in the "users" array, under a certain condition
"company": {
"type" : "01",
"information":
{
"job":
{
"job_name": "N",
"job_address": 1670392687114,
"job_salary": 1234567890123,
"contacts": 0
},
"users":
[
{
"id": 1,
"name": "Alex",
"rate": 4,
"address": "bla bla bla"
},
{
"id": 2,
"name": "Jenifer",
"rate": 5,
"address": "bla bla bla"
}
]
}
}
My logic is next:
if tuple.type == "01" or tuple.type == "02" or tuple.type == "03" or tuple.type == "04" then
for _, attr in pairs(users) do
attr.status = "UPDATED"
end
end
Is it correct to add a new status="UPDATED" field to each object in the array "users" here?
Does this entry exist?
And yet, tell me please, can I somehow make the condition in if more beautiful? For example analog in Java list.contains()
Updated:
The final version after adding new field "status" should look like this (see image)
Is it correct to add a new status="UPDATED" field to each object in
the array "users" here? Does this entry exist?
If you want the table to have a status field with value "UPDATED" then attr.status = "UPDATED"is correct.
This only makes sense if you'll add more non-updated users to that table later though as you're updating the entire list. you could as well just mark the users table object as updated.
And yet, tell me please, can I somehow make the condition in if more
beautiful? For example analog in Java list.contains()
No but you could write your own function.
function table.contains(tbl, value)
for _, v in pairs(tbl) do
if (v == value) then return true end
end
return false
end
if table.contains({"01", "02", "03", "04"}, tuple.type) then
for _, attr in pairs(users) do
attr.status = "UPDATED"
end
end
Alternatively you could use a lookup table
local isUpdateType = {
["01"] = true,
["02"] = true,
["03"] = true,
["04"] = true,
}
and later
if isUpdateType[tuple.type] then end
How to solve this depends very much on what you consider "beautiful" here.
I'm trying to combine requests from two services in one endpoint.
The first returns the list of users, like this:
{
"data": [
{ "id": 1, "name": "first", "photo": "employee_photos/key1.png" },
{ "id": 2, "name": "second", "photo": null },
{ "id": 3, "name": "third", "photo": "employee_photos/key3.png" }
]
}
The second is supposed to receive the POST request with the JSON listing photo keys to get the required version URLs.
Request:
{
"keys": [ "employee_photos/key1.png", "employee_photos/key3.png" ],
"versions": [ "small", "large" ]
}
I created a small Lua script to process the response of the first request and collect the list of keys. It looks like this:
function post_employees(request, employeesResponse)
local resp = employeesResponse.load()
local data = resp:data():get("data")
local photo_keys = {}
for i = 0, data:len() - 1, 1 do
local rec = data:get(i)
local id = rec:get("id")
local photo = rec:get("photo")
if photo then
table.insert(photo_keys, photo)
end
end
resp:data():set("photos", table.concat(photo_keys, ","))
end
But then... I can't find a way to use this list of keys in the second request. Is it even possible?
This is my column:
[
{ id: 1, value: 1, complete: true },
{ id: 2, value: 1, complete: false },
{ id: 3, value: 1, complete: true }
]
First, is there a "correct" way to work with a jsonb scheme? should I redesign to work with a single json instead of the array of hashes?
I have about 200 entries on the database, the column status has 200 of those itens.
How would I perform a query to get the count of true/false?
How can I query for ALL complete itens? I can query for the database rows in which the json has an item complete, but I can't query for all the itens, in all rows of the database that are complete.
Appreciate the help, thank you
Aha! I found it here:
https://levelup.gitconnected.com/how-to-query-a-json-array-of-objects-as-a-recordset-in-postgresql-a81acec9fbc5
Say your dataset is like this:
[{
"productid": "3",
"name": "Virtual Keyboard",
"price": "150.00"
}, {
"productid": "1",
"name": "Dell 123 Laptop Computer",
"price": "1300.00"
},
{
"productid": "8",
"name": "LG Ultrawide Monitor",
"price": "190.00"
}]
The proper way to count it, is like this:
select items.name, count(*) as num from
purchases,jsonb_to_recordset(purchases.items_purchased) as items(name text)
group by items.name
order by num Desc
Works like a charm and is extremely fast.
To do it in Rails, you need to use Model.find_by_sql(....) and indicate your select therem. I'm sure there are probably better ways to do it.
I have a performance issue in my application. I would like to gather some ideas on what I can do to improve it. The application is very easy: I need to add values inside a nested table to get the total an user wants to pay out of all the pending payments. The user chooses a number of payments and I calculate how much it is they will pay.
This is what I have:
jsonstr = "{ "name": "John",
"surname": "Doe",
"pending_payments": [
{
"month": "january",
"amount": 50,
},
{
"month": "february",
"amount": 40,
},
{
"month": "march",
"amount": 45,
},
]
}"
local lunajson = require 'lunajson'
local t = lunajson.decode(jsonstr)
local limit -- I get this from the user
local total = 0;
for i=1, limit, 1 do
total = total + t.pending_payments[i].amount;
end;
It works. At the end I get what I need. However, I notice that it takes ages to do the calculation. Each JSON has only twelve pending payments (one per month). It is taking between two to three seconds to come up with a result!. I tried in different machines and LUA 5.1, 5.2., 5.3. and the result is the same.
Can anyone please suggest how I can implement this better?
Thank you!
For this simple string, try the test code below, which extracts the amounts directly from the string, without a json parser:
jsonstr = [[{ "name": "John",
"surname": "Doe",
"pending_payments": [
{
"month": "january",
"amount": 50,
},
{
"month": "february",
"amount": 40,
},
{
"month": "march",
"amount": 45,
},
]
}]]
for limit=0,4 do
local total=0
local n=0
for a in jsonstr:gmatch('"amount":%s*(%d+),') do
n=n+1
if n>limit then break end
total=total+tonumber(a)
end
print(limit,total)
end
I found the delay had nothing to do with the calculation in LUA. It was related with a configurable delay in the retrieval of the limit variable.
I have nothing to share here related to the question asked since the problem was actually in an external element.
Thank #lfh for your replies.
I'm using a Ruby script to interface with an application API and the results being returned are in a JSON format. For example:
{
"incidents": [
{
"number": 1,
"status": "open",
"key": "abc123"
}
{
"number": 2,
"status": "open",
"key": "xyz098"
}
{
"number": 3,
"status": "closed",
"key": "lmn456"
}
]
}
I'm looking to search each block for a particular "key" value (yzx098 in this example) and return the associated "number" value.
Now, I'm very new to Ruby and I'm not sure if there's already a function to help accomplish this. However, a couple days of scouring the Googles and Ruby resource books hasn't yielded anything that works.
Any suggestions?
First of all, the JSON should be as below: (note the commas)
{
"incidents": [
{
"number": 1,
"status": "open",
"key": "abc123"
},
{
"number": 2,
"status": "open",
"key": "xyz098"
},
{
"number": 3,
"status": "closed",
"key": "lmn456"
}
]
}
Strore the above json in a variable
s = '{"incidents": [{"number": 1,"status": "open","key": "abc123"},{"number": 2,"status": "open","key": "xyz098"},{"number": 3,"status": "closed","key": "lmn456"}]}'
Parse the JSON
h = JSON.parse(s)
Find the required number using map
h["incidents"].map {|h1| h1['number'] if h1['key']=='xyz098'}.compact.first
Or you could also use find as below
h["incidents"].find {|h1| h1['key']=='xyz098'}['number']
Or you could also use select as below
h["incidents"].select {|h1| h1['key']=='xyz098'}.first['number']
Do as below
# to get numbers from `'key'`.
json_hash["incidents"].map { |h| h['key'][/\d+/].to_i }
json_hash["incidents"] - will give you the value of the key "incidents", which is nothing but an array of hash.
map to iterate thorough each hash and collect the value of 'key'. Then applying Hash#[] to each inner hash of the array, to get the value of "key". Then calling str[regexp], to get only the number strings like '098' from "xyz098", finally applying to_i to get the actual integer from it.
If the given hash actually a json string, then first parse it using JSON::parse to convert it to a hash.Then do iterate as I said above.
require 'json'
json_hash = JSON.parse(json_string)
# to get values from the key `"number"`.
json_hash["incidents"].map { |h| h['number'] } # => [1, 2, 3]
# to search and get all the numbers for a particular key match and take the first
json_hash["incidents"].select { |h| h['key'] == 'abc123' }.first['number'] # => 1
# or to search and get only the first number for a particular key match
json_hash["incidents"].find { |h| h['key'] == 'abc123' }['number'] # => 1