Append Data to Json Array Issue

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



Leave a reply



Submit