2

この PHP スクリプトは、JSON オブジェクト (配列) の 1 つに要素を追加します。

#!/usr/bin/php
<?php

$filename = 'composer.json';
$obj = json_decode(file_get_contents($filename, true));

if (null === $obj) {
   throw new Exception(json_last_error()); // this will just be an error code
}

$obj->require = (object) array_merge((array) $obj->require, array('friendsofsymfony/user-bundle' => "*"));

file_put_contents(
    $filename,
    json_encode($obj)
);

問題は、ファイル形式がめちゃくちゃになることです。

スクリプトを使用する前に、編集中のファイルは次のようになります。

{
    "name": "symfony/framework-standard-edition",
    "description": "The \"Symfony Standard Edition\" distribution",
    "autoload": {
        "psr-0": { "": "src/" }
    },
    "require": {
        "php": ">=5.3.3",
        "symfony/symfony": "2.1.*",
        "doctrine/orm": ">=2.2.3,<2.4-dev",
        "doctrine/doctrine-bundle": "1.0.*",
        "twig/extensions": "1.0.*",
        "symfony/assetic-bundle": "2.1.*",
        "symfony/swiftmailer-bundle": "2.1.*",
        "symfony/monolog-bundle": "2.1.*",
        "sensio/distribution-bundle": "2.1.*",
        "sensio/framework-extra-bundle": "2.1.*",
        "sensio/generator-bundle": "2.1.*",
        "jms/security-extra-bundle": "1.2.*",
        "jms/di-extra-bundle": "1.1.*"
    },
    "scripts": {
        "post-install-cmd": [
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile"
        ],
        "post-update-cmd": [
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets",
            "Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile"
        ]
    },
    "minimum-stability": "dev",
    "extra": {
        "symfony-app-dir": "app",
        "symfony-web-dir": "web"
    }
}

スクリプトを実行した後。私はこれを得る:

{"name":"symfony\/framework-standard-edition","description":"The \"Symfony Standard Edition\" distribution","autoload":{"psr-0":{"_empty_":"src\/"}},"require":{"php":">=5.3.3","symfony\/symfony":"2.1.*","doctrine\/orm":">=2.2.3,<2.4-dev","doctrine\/doctrine-bundle":"1.0.*","twig\/extensions":"1.0.*","symfony\/assetic-bundle":"2.1.*","symfony\/swiftmailer-bundle":"2.1.*","symfony\/monolog-bundle":"2.1.*","sensio\/distribution-bundle":"2.1.*","sensio\/framework-extra-bundle":"2.1.*","sensio\/generator-bundle":"2.1.*","jms\/security-extra-bundle":"1.2.*","jms\/di-extra-bundle":"1.1.*","friendsofsymfony\/user-bundle":"*"},"scripts":{"post-install-cmd":["Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap","Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache","Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets","Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile"],"post-update-cmd":["Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::buildBootstrap","Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::clearCache","Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installAssets","Sensio\\Bundle\\DistributionBundle\\Composer\\ScriptHandler::installRequirementsFile"]},"minimum-stability":"dev","extra":{"symfony-app-dir":"app","symfony-web-dir":"web"}}

改行などはすべて失われます。

私の PHP バージョンは 5.3.10 です。つまり、エンコードに「PRETTY_PRINT」オプションがある PHP 5.4 を使用できません。

json_encode(); を使用して PHP 5.3.10 でファイル構造を保持する方法はありますか?

4

4 に答える 4

3

使用print_r:

$pretty_json = print_r(json_decode($arr, true), true);

jsonファイルが正確に必要であることを認識し、この機能を確認してください

于 2012-11-15T11:04:42.480 に答える
1

残念ながら違います。

データはマシンで使用することを目的としているため、これは大きな問題ではありません。視覚的に検査したい場合は、コンテキストに応じて自動的にきれいな印刷を行うツールがいくつかあります。

于 2012-11-15T11:04:33.463 に答える
0

Denis Ermolinが提供する関数を使用し、str_replace()を追加しました。

<?php

$filename = 'composer.json';
$obj = json_decode(file_get_contents($filename, true));

if (null === $obj) {
   throw new Exception(json_last_error()); // this will just be an error code
}

$obj->require = (object) array_merge((array) $obj->require, array('friendsofsymfony/user-bundle' => "*"));

file_put_contents($filename,pretty_json(json_encode($obj)));

function pretty_json($json) {
    $result      = '';
    $pos         = 0;
    $strLen      = strlen($json);
    $indentStr   = '  ';
    $newLine     = "\n";
    $prevChar    = '';
    $outOfQuotes = true;
    for ($i=0; $i<=$strLen; $i++) {
        // Grab the next character in the string.
        $char = substr($json, $i, 1);
        // Are we inside a quoted string?
        if ($char == '"' && $prevChar != '\\') {
            $outOfQuotes = !$outOfQuotes;
        // If this character is the end of an element, 
        // output a new line and indent the next line.
        } else if(($char == '}' || $char == ']') && $outOfQuotes) {
            $result .= $newLine;
            $pos --;
            for ($j=0; $j<$pos; $j++) {
                $result .= $indentStr;
            }
        }
        // Add the character to the result string.
        $result .= $char;
        // If the last character was the beginning of an element, 
        // output a new line and indent the next line.
        if (($char == ',' || $char == '{' || $char == '[') && $outOfQuotes) {
            $result .= $newLine;
            if ($char == '{' || $char == '[') {
                $pos ++;
            }
            for ($j = 0; $j < $pos; $j++) {
                $result .= $indentStr;
            }
        }
        $prevChar = $char;
    }
    $result = str_replace("\\/", "/", $result);
    return $result;
}
?>

または、PHP5.4にアップデートしてPRETTY_PRINT...

于 2012-11-15T13:40:18.517 に答える
0

なぜフォーマットが重要なのですか?確かに、これはプログラム/プロセスが消費するためのものであり、人間が読みやすくする必要がありませんか?

JSON フィードを表示するための便利な Google Chrome 拡張機能があります。

https://chrome.google.com/webstore/detail/json-formatter/bcjindcccaagfpapjjmafapmmgkkhgoa

于 2012-11-15T12:32:51.340 に答える