I would like to add an object into a existing json object :
My existing json object :
{
"id": 1,
"horaire_id": 1,
"json": "{"i": "idHoraire1-NumReservation1", "x": 3, "y": 2, "w":5, "h": 3, "j": 0}",
"num_reserv": 1,
"nombre_heures": 7.5,
"created_at": "2021-09-16T13:55:00.000000Z",
"updated_at": "2021-09-16T13:55:03.000000Z"
}
And the object to insert into the existing json object :
{
"id": 1,
"evenement_type_id": 1,
"reservation_id": 1,
"posinreserv": 1,
"campus_id": 1,
"comment": null,
"created_at": null,
"updated_at": null
}
We tried json_encode and json_decode, without success :
$reservation = json_decode($reservation, true)
All this with Laravel 7 (not is js)
Thank you.
$data1 = '{
"id": 1,
"horaire_id": 1,
"json": "{"i": "idHoraire1-NumReservation1", "x": 3, "y": 2, "w":5, "h": 3, "j": 0}",
"num_reserv": 1,
"nombre_heures": 7.5,
"created_at": "2021-09-16T13:55:00.000000Z",
"updated_at": "2021-09-16T13:55:03.000000Z"
}';
$data2 = '{
"id": 1,
"evenement_type_id": 1,
"reservation_id": 1,
"posinreserv": 1,
"campus_id": 1,
"comment": null,
"created_at": null,
"updated_at": null
}';
Laravel
$array = array_merge($data1->toArray(), $data2->toArray());
PHP
$array = array_merge(array($data1), array($data2));
You can use the spread operator: (note json objects are just arrays in php, assuming you've json_decoded it)
$result = [...$array_1, ...$array_2]
or
$result = array_merge($array_1, $array_2)
Related
I have 2 JSON-files and I need to compare them.
json_new.json
{"company_id": 111111, "resource": "record", "resource_id": 406155061, "status": "create", "data": {"id": 11111111, "company_id": 111111, "services": [{"id": 22222225, "title": "\u0421\u0442\u0440\u0438\u0436\u043a\u0430", "cost": 1500, "cost_per_unit": 1500, "first_cost": 1500, "amount": 1}], "goods_transactions": [], "staff": {"id": 1819441, "name": "\u041c\u0430\u0441\u0442\u0435\u0440"}, "client": {"id": 130345867, "name": "\u041a\u043b\u0438\u0435\u043d\u0442", "phone": "79111111111", "success_visits_count": 2, "fail_visits_count": 0}, "clients_count": 1, "datetime": "2022-01-25T13:00:00+03:00", "create_date": "2022-01-22T00:54:00+03:00", "online": false, "attendance": 2, "confirmed": 1, "seance_length": 3600, "length": 3600, "master_request": 1, "visit_id": 346427049, "created_user_id": 10573443, "deleted": false, "paid_full": 1, "last_change_date": "2022-01-22T00:54:00+03:00", "record_labels": "", "date": "2022-01-22 10:00:00"}}
json_old.json
{"company_id": 111111, "resource": "record", "resource_id": 406155061, "status": "create", "data": {"id": 11111111, "company_id": 111111, "services": [{"id": 9035445, "title": "\u0421\u0442\u0440\u0438\u0436\u043a\u0430", "cost": 1500, "cost_per_unit": 1500, "first_cost": 1500, "amount": 1}], "goods_transactions": [], "staff": {"id": 1819441, "name": "\u041c\u0430\u0441\u0442\u0435\u0440"}, "client": {"id": 130345867, "name": "\u041a\u043b\u0438\u0435\u043d\u0442", "phone": "79111111111", "success_visits_count": 2, "fail_visits_count": 0}, "clients_count": 1, "datetime": "2022-01-25T11:00:00+03:00", "create_date": "2022-01-22T00:54:00+03:00", "online": false, "attendance": 0, "confirmed": 1, "seance_length": 3600, "length": 3600, "master_request": 1, "visit_id": 346427049, "created_user_id": 10573443, "deleted": false, "paid_full": 0, "last_change_date": "2022-01-22T00:54:00+03:00", "record_labels": "", "date": "2022-01-22 10:00:00"}}
In these files, you need to compare the individual parts specified in diff_list:
diff_list = ["services", "staff", "datetime"]
Also code should print result in console, copy and transfer result copy to the file called result.json
My code
import data as data
import json
# JSON string
with open('json_old.json') as json_1:
json1_dict = json.load(json_1)
with open('json_new.json') as json_2:
json2_dict = json.load(json_2)
diff_list = ["services", "staff", "datetime"]
result = [
(sorted(json1_dict.items())),
(sorted(json2_dict.items()))
]
print(sorted(json1_dict.items()) == sorted(json2_dict.items()))
with open('result.json', 'w') as f:
json.dump(result, f)
This code is actually works but I need to catch the change of certain parameters specified in diff_list and output the value: what has changed and for what.
Thank you for your support, guys :)
To catch what has changed between json1_dict and json2_dict, you can use the following one line, making good use of "dictionary comprehension":
changed_items = {k: [json1_dict[k], json2_dict[k]] for k in json1_dict if k in json2_dict and json1_dict[k] != json2_dict[k]}
Every key of changed_items will contain two values, first of json1_dict and second of json2_dict. If the changed_items you are interested in must be the keys in diff_list, then you need instead to change a little the condition within the expression:
changed_items = {k: [json1_dict[k], json2_dict[k]] for k in json1_dict if k in json2_dict and k in diff_list and json1_dict[k] != json2_dict[k]}
all you need afterwards is to print(changed_items)
import json
# Load JSON files
with open('json_old.json') as json_file1:
json1_dict = json.load(json_file1)
with open('json_new.json') as json_file2:
json2_dict = json.load(json_file2)
diff_list = ["services", "staff", "datetime"]
# Compare the parts specified in diff_list and print the differences
result = {}
for key in diff_list:
if json1_dict['data'][key] != json2_dict['data'][key]:
result[key] = {
'old_value': json1_dict['data'][key],
'new_value': json2_dict['data'][key]
}
print(result)
# Write the differences to a result.json file
with open('result.json', 'w') as outfile:
json.dump(result, outfile)
This code snippet will compare the JSON files and print the differences in the parts specified in the diff_list variable to the console. It will also write the differences to a file named result.json.
I am using Eloquent Relationship in Laravel to output my data to JSON. When I use Eloquent Relations they show up inside JSON as an object but I need only JSON output with variables inside without object or json, As shown below:
{
"id": 1,
"name": "Status changed",
"history_id": null,
"admin_id": 4,
"created_at": "2021-05-21T16:10:08.000000Z",
"updated_at": "2021-04-21T16:10:08.000000Z",
"type_id": 2,
"comment": "Horoshiy Specialist",
"result_id": 2,
"result_comment": "Prowerili anketu i obrazowanie",
"start_time": null,
"end_time": null,
},
Instead of this (the result for the relation one to many toJSON in LARVEL) :
$activity = Activity::find(1)->load('history')->toJSON();
result:
{
"id": 1,
"name": "Status changed",
"history_id": null,
"admin_id": 4,
"created_at": "2021-05-21T16:10:08.000000Z",
"updated_at": "2021-04-21T16:10:08.000000Z",
"history": [
{
"id": 1,
"type_id": 2,
"comment": "Horoshiy Specialist",
"result_id": 2,
"result_comment": "Prowerili anketu i obrazowanie",
"start_time": null,
"end_time": null,
}
]
},
Any ideas how this can be done ? I can do it using DB join (), but is there a way to do it using Eloquent? Besides :
$activity = \App\Models\Activity::find(1)
->join('activity_history', 'activity_history.id', '=',
'activities.history_id')->select('*')->get()
->toJSON();
Because this is not the best way to do it, because I am using the column names and the table names, which I have to go to the DB behind to look at them
You can around doing this by flattening the array when you get that result. Let's imagine you $object->history to get the result with the history relationship, and simply do:
Arr::dot($object->history);
So you'll get an array like:
{
"id": 1,
"name": "Status changed",
"history_id": null,
"admin_id": 4,
"created_at": "2021-05-21T16:10:08.000000Z",
"updated_at": "2021-04-21T16:10:08.000000Z",
"history.id": 1,
"history.type_id": 2,
"history.comment": "Horoshiy Specialist",
"history.result_id": 2,
"history.result_comment": "Prowerili anketu i obrazowanie",
"history.start_time": null,
"history.end_time": null,
}
need to ask,
currently i'm using laravel and db query builder to create the function below.
Requirement is to get the query result without the bracket / object but with { }
Function is below :
$score = DB::table('m_player_scorecard')
->where('session_id', '=', $sessionID)
->orderBy('created_at', 'desc')
->get();
$scoreArr = json_decode(json_encode($score), true);
return response()
->json($scoreArr);
when i try to hit from postman :
[
{
"id": 153,
"session_id": "9e3bb8296fd195c66ced470ec50301385f6cd31a17012e26fd0099bdf821338c",
"round_order": 2,
"player_one_id": 1,
"score_one": 10,
"player_two_id": 2,
"score_two": 10,
"player_three_id": 3,
"score_three": 30,
"player_four_id": 4,
"score_four": 40,
"notes": null,
"created_at": "2020-06-06 18:15:27",
"updated_at": null
},
{
"id": 152,
"session_id": "9e3bb8296fd195c66ced470ec50301385f6cd31a17012e26fd0099bdf821338c",
"round_order": 1,
"player_one_id": 1,
"score_one": 10,
"player_two_id": 2,
"score_two": 20,
"player_three_id": 3,
"score_three": 30,
"player_four_id": 4,
"score_four": 40,
"notes": null,
"created_at": "2020-06-06 18:14:39",
"updated_at": null
}
]
I need to change the bracket [ ] to { }.
How to do that?
Thanks before
You have updated your question, so I updated my answer :
$remove = array("[", "]");
$replace = array("{", "}");
$newJson = str_replace($remov, $replace, $oldJson);
I'm making an API GET call using Ruby - the call is made to a Learning Management System and returns the following JSON:
{
"id": 12345,
"body": null,
"url": null,
"grade": "75",
"score": 75,
"submitted_at": "2020-05-02T11:30:53Z",
"assignment_id": 9876,
"user_id": 1111,
"submission_type": "online_upload",
"workflow_state": "graded",
"grade_matches_current_submission": true,
"graded_at": "2017-06-05T08:47:49Z",
"grader_id": 2222,
"attempt": 1,
"cached_due_date": "2020-05-03T15:00:00Z",
"excused": false,
"late_policy_status": null,
"points_deducted": null,
"grading_period_id": null,
"late": false,
"missing": false,
"seconds_late": 0,
"entered_grade": "75",
"entered_score": 75,
"preview_url": "https://etcetc",
"turnitin_data": {
"attachment_33333": {
"status": "scored",
"object_id": "44444444",
"similarity_score": 0,
"web_overlap": 0,
"publication_overlap": 0,
"student_overlap": 0,
"state": "none"
}
},
"attachments": [
{
"id": 33333,
"uuid": "kjsdkjhsdfkhsfd",
"folder_id": 55555,
"display_name": "Submission.pdf",
"filename": "Submission.pdf",
"content-type": "application/pdf",
"url": "https://etcetc",
"size": 2668226,
"created_at": "2020-05-02T11:30:51Z",
"updated_at": "2020-06-06T15:01:46Z",
"unlock_at": null,
"locked": false,
"hidden": false,
"lock_at": null,
"hidden_for_user": false,
"thumbnail_url": null,
"modified_at": "2020-05-02T11:30:51Z",
"mime_class": "pdf",
"media_entry_id": null,
"locked_for_user": false,
"preview_url": "api/etcetc"
}
],
"submission_comments": [
{
"id": 99999,
"comment": "here’s a comment",
"author_id": 1,
"author_name": "Mickey Mouse",
"created_at": "2020-05-15T12:54:08Z",
"edited_at": null,
"avatar_path": "/images/users/1",
"author": {
"id": 1,
"display_name": " Mickey Mouse ",
"avatar_image_url": "https://etcetc",
"html_url": "https://etcetc"
}
},
{
"id": 223344,
"comment": "another comment",
"author_id": 2,
"author_name": "Donald Duck",
"created_at": "2020-06-05T10:48:51Z",
"edited_at": null,
"avatar_path": "/images/users/2",
"author": {
"id": 2,
"display_name": "Donald Duck",
"avatar_image_url": "https://etcetc",
"html_url": "https://etcetc"
}
}
]
}
I need to be able to retrieve specific values from "submission_comments", namely the values for "comment", "author_id" and "author_name". At the moment the best I can do is retrieve "submission_comments" as one big entity. Here's how I'm getting that far:
require 'typhoeus'
require 'link_header'
require 'json'
require 'csv'
the_url = 'https://etctetc'
token = 'mytoken'
api_endpoint = '/api/etc'
output_csv = 'C:\Users\me\Desktop\Ruby Canvas course\assignment_comments.csv'
CSV.open(output_csv, 'wb') do |csv|
csv << ["user_id", "TII", "marker"]
end
request_url = "#{the_url}#{api_endpoint}"
count = 0
more_data = true
while more_data
get_comments = Typhoeus::Request.new(
request_url,
method: :get,
headers: { authorization: "Bearer #{token}" }
)
get_comments.on_complete do |response|
#get next link
links = LinkHeader.parse(response.headers['link']).links
next_link = links.find { |link| link['rel'] == 'next' }
request_url = next_link.href if next_link
if next_link && "#{response.body}" != "[]"
more_data = true
else
more_data = false
end
if response.code == 200
data = JSON.parse(response.body)
data.each do |comments|
CSV.open(output_csv, 'a') do |csv|
csv << [comments['id'], comments['turnitin_data'], comments['submission_comments']]
end
end
else
puts "Something went wrong! Response code was #{response.code}"
end
end
get_comments.run
end
puts "Script done running"
I'm new to this (the ruby code is based on an exercise so I may not fully understand it)- any help/advice would be really appreciated!
EDIT: I should also note that this isn't the total JSON response I'm dealing with - this is just one of ten items that are returned
"submission_comments": [
{
"id": 99999,
}
]
the [] means it is array. {} means it is an object.
So you probably need to do something like this:
json["submission_comments"].first["id"]
or better iterate through it:
ids = json["submission_comments"].map{|comment| comment["id"]}
I'm able to get the variables you need if you can read the JSON file in as text, then use Ruby's JSON.parse(...) method on it. I think the main problem is that JSON uses null but Ruby hashes use nil. You could do a string replace or try something like this (I did not modify your JSON, only put it into a single quoted string):
json_text = '{
"id": 12345,
"body": null,
"url": null,
"grade": "75",
"score": 75,
"submitted_at": "2020-05-02T11:30:53Z",
"assignment_id": 9876,
"user_id": 1111,
"submission_type": "online_upload",
"workflow_state": "graded",
"grade_matches_current_submission": true,
"graded_at": "2017-06-05T08:47:49Z",
"grader_id": 2222,
"attempt": 1,
"cached_due_date": "2020-05-03T15:00:00Z",
"excused": false,
"late_policy_status": null,
"points_deducted": null,
"grading_period_id": null,
"late": false,
"missing": false,
"seconds_late": 0,
"entered_grade": "75",
"entered_score": 75,
"preview_url": "https://etcetc",
"turnitin_data": {
"attachment_33333": {
"status": "scored",
"object_id": "44444444",
"similarity_score": 0,
"web_overlap": 0,
"publication_overlap": 0,
"student_overlap": 0,
"state": "none"
}
},
"attachments": [
{
"id": 33333,
"uuid": "kjsdkjhsdfkhsfd",
"folder_id": 55555,
"display_name": "Submission.pdf",
"filename": "Submission.pdf",
"content-type": "application/pdf",
"url": "https://etcetc",
"size": 2668226,
"created_at": "2020-05-02T11:30:51Z",
"updated_at": "2020-06-06T15:01:46Z",
"unlock_at": null,
"locked": false,
"hidden": false,
"lock_at": null,
"hidden_for_user": false,
"thumbnail_url": null,
"modified_at": "2020-05-02T11:30:51Z",
"mime_class": "pdf",
"media_entry_id": null,
"locked_for_user": false,
"preview_url": "api/etcetc"
}
],
"submission_comments": [
{
"id": 99999,
"comment": "here’s a comment",
"author_id": 1,
"author_name": "Mickey Mouse",
"created_at": "2020-05-15T12:54:08Z",
"edited_at": null,
"avatar_path": "/images/users/1",
"author": {
"id": 1,
"display_name": " Mickey Mouse ",
"avatar_image_url": "https://etcetc",
"html_url": "https://etcetc"
}
},
{
"id": 223344,
"comment": "another comment",
"author_id": 2,
"author_name": "Donald Duck",
"created_at": "2020-06-05T10:48:51Z",
"edited_at": null,
"avatar_path": "/images/users/2",
"author": {
"id": 2,
"display_name": "Donald Duck",
"avatar_image_url": "https://etcetc",
"html_url": "https://etcetc"
}
}
]
}'
Part I added:
ruby_hash = JSON.parse(json_text)
submission_comments = ruby_hash["submission_comments"]
submission_comments.each do |submission_comment|
comment = submission_comment["comment"]
author_id = submission_comment["author_id"]
author_name = submission_comment["author_name"]
puts "Comment: #{comment}, Author ID: #{author_id}, Author Name: #{author_name}\n\n"
end
Terminal Result:
=> Comment: here’s a comment, Author ID: 1, Author Name: Mickey Mouse
=> Comment: another comment, Author ID: 2, Author Name: Donald Duck
Edit: I added a jenky af one-liner version just for fun (presuming the json_text variable above is already initialized)
JSON.parse(json_text)["submission_comments"]
.map{|txt| puts(["comment","author_id","author_name"]
.map{|k| k.instance_eval{"#{upcase}: #{txt[to_s]}"}}.join(', '))}
COMMENT: here’s a comment, AUTHOR_ID: 1, AUTHOR_NAME: Mickey Mouse
COMMENT: another comment, AUTHOR_ID: 2, AUTHOR_NAME: Donald Duck
I've used pymongo to connect to mongo replica set and print the status of replica set using json dump. I want to parse this output and display "name" and "stateStr" into a list or array for the user to be able to pick a particular host.Here is my json dump output:
{
{
"replSetGetStatus": {
"date": "2016-10-07T14:21:25",
"members": [
{
"_id": 0,
"health": 1.0,
"name": "xxxxxxxxxxx:27017",
"optime": null,
"optimeDate": "2016-10-07T13:50:11",
"self": true,
"state": 1,
"stateStr": "PRIMARY",
"uptime": 32521
},
{
"_id": 1,
"health": 1.0,
"lastHeartbeat": "2016-10-07T14:21:24",
"lastHeartbeatRecv": "2016-10-07T14:21:24",
"name": "xxxxxxxxxxxx:27017",
"optime": null,
"optimeDate": "2016-10-07T13:50:11",
"pingMs": 0,
"state": 2,
"stateStr": "SECONDARY",
"syncingTo": "xxxxxxxxxxxx:27017",
"uptime": 27297
},
{
"_id": 2,
"health": 1.0,
"lastHeartbeat": "2016-10-07T14:21:24",
"lastHeartbeatRecv": "2016-10-07T14:21:24",
"name": "xxxxxxxxxxxxx:27020",
"pingMs": 0,
"state": 7,
"stateStr": "ARBITER",
"uptime": 32517
}
],
"myState": 1,
"ok": 1.0,
"set": "replica1"
}
}
Please try below Javascript code. It worked for me.
use admin;
var result = rs.status();
var length = result.members.length;
for (var i=0;i<length;i++){
print ("Server Name-" +result.members[i].name);
print ("Server State-" +result.members[i].stateStr);
}