I know JSON does not work by index like an array, but i'm looking for a way to add a new JSON element on a specific position within the JSON object.
Let's say i have an array with JSON objects:
[
{
"key": value,
"key": value,
"key": value,
},
{
"key": value,
"key": value,
"key": value,
}
]
And i want to add a new element in each JSON object on the second position.
[
{
"key": value,
** Enter new key/value here **
"key": value,
"key": value,
},
{
"key": value,
** Enter new key/value here **
"key": value,
"key": value,
}
]
Any ideas on how to accomplish this?
Thanks in advance!
JavaScript objects (upon which JSON is based) do not remember insertion order.
If serialization/deserialization is not needed, you can use Map objects, which have key=>value pairs with insertion order.
In case you need to serialize/deserialize, then its better to convert the JSON object, to a JSON array of single pair objects, instead like [{"a":"z"}, {"b":"y"}, {"c","x}] etc.
There is no such thing in JSON as order by key or value. It works as key-value-pairs