Append data to JSON array using PHP
$accountData
is an object, as it should be. Array access is not valid:
array_push($accountData->loginHistory, $newLoginHistory);
// or simply
$accountData->loginHistory[] = $newLoginHistory;
Appending JSON array object to formdata
If your API accepts your data in that format, you cannot send it as JSON, you need to create a separate FormData
entry for each of the lines you've mentioned.
For example
const contacts = [{ "Country":"country 1", "Phone":"123" },{ "Country":"country 2", "Phone":"456" }];
var formdata = new FormData();
// This could be made fancier but it explains how to fix the problem
for (let i=0; i < contacts.length; i++) {
formdata.append(`Contacts[${i}].Country`, contacts[i].Country);
formdata.append(`Contacts[${i}].Phone`, contacts[i].Phone);
}
Note that json-form-data does it for you
const data = {
Contacts: [{
"Country": "country 1",
"Phone": "123"
}, {
"Country": "country 2",
"Phone": "456"
}]
};
const formData = jsonToFormData(data);
for (const [key,value] of formData.entries()) {
console.log(`${key}: ${value}`);
}
<script src="https://unpkg.com/json-form-data@^1.7.0/dist/jsonToFormData.min.js"></script>
append json array using jq
There are several issues with your script. Generally, this should work (but still needs improvement on certain levels):
JSON='[{"name": "Jon", "class": "senior"}]'
echo "$JSON" | jq '. += [{"new_key": "new_value"}]'
[
{
"name": "Jon",
"class": "senior"
},
{
"new_key": "new_value"
}
]
Related Topics
How to Reload a Page With React-Router
How to Get Only 1St Element of Json Data
Retrieving Keys from Json Array Key-Value Pair Dynamically - JavaScript
Regex in JavaScript Allow Only Numbers and One Dot Followed by Max 2 Number
How to Show Which Question a User Is on When Taking My Quiz
Regular Expression for Not Allowing Spaces in the Input Field
How to Get Around .Push Is Not a Function in JavaScript
How to Add Multiple Values in Json Object and Get an Updated Json File
How to Get the Name of the Current Windows User in JavaScript
Regex to Replace Everything Except Numbers and a Decimal Point
Foreach Is Not a Function Error With JavaScript Array
How to Make a Bot Delete Messages After a Certain Time Period
How to Print Star Pattern in JavaScript in a Very Simple Manner
Click on Pseudo Element Using Selenium
How to Show Roles of User Discord.Js/Userinfo Command