Reputation: 322
Let's have a file.json
containing a JSON, e.g.
{
"first-key": "foo",
"second-key": "bar"
}
Now if I encode and decode the JSON with PHP built-in functions, it changes the formatting. Is there a way how to do this without reformatting the JSON?
I need to add a single key and the file is committed in Git. Hence, I want to avoid changing lines that didn't really change.
Upvotes: 0
Views: 183
Reputation: 17417
The JSON_PRETTY_PRINT flag is as close as you're going to get without manually editing the json-encoded string. It looks like it should work for your example though.
<?php
$json = '{
"first-key": "foo",
"second-key": "bar"
}';
$arr = json_decode($json, true);
$arr['second-key'] = 'baz';
print_r(json_encode($arr, JSON_PRETTY_PRINT));
=
{
"first-key": "foo",
"second-key": "baz"
}
Upvotes: 1
Reputation: 5689
<?php
$json = '{
"first-key": "foo",
"second-key": "bar"
}';
$arr = json_decode($json, true);
echo "<pre>";
print_r($arr);
echo "</pre>";
$arr_new = array("newKey"=>$arr);
$json_new = json_encode($arr_new);
echo $json_new;
?>
Upvotes: 0