JSON Lint for PHP

Last update: May 18, 2022

JSON Lint

Build Status

Usage

use Seld\JsonLint\JsonParser;

$parser = new JsonParser();

// returns null if it's valid json, or a ParsingException object.
$parser->lint($json);

// Call getMessage() on the exception object to get
// a well formatted error message error like this

// Parse error on line 2:
// ... "key": "value"    "numbers": [1, 2, 3]
// ----------------------^
// Expected one of: 'EOF', '}', ':', ',', ']'

// Call getDetails() on the exception to get more info.

// returns parsed json, like json_decode() does, but slower, throws
// exceptions on failure.
$parser->parse($json);

You can also pass additional flags to JsonParser::lint/parse that tweak the functionality:

  • JsonParser::DETECT_KEY_CONFLICTS throws an exception on duplicate keys.
  • JsonParser::ALLOW_DUPLICATE_KEYS collects duplicate keys. e.g. if you have two foo keys they will end up as foo and foo.2.
  • JsonParser::PARSE_TO_ASSOC parses to associative arrays instead of stdClass objects.

Example:

$parser = new JsonParser;
try {
    $parser->parse(file_get_contents($jsonFile), JsonParser::DETECT_KEY_CONFLICTS);
} catch (DuplicateKeyException $e) {
    $details = $e->getDetails();
    echo 'Key '.$details['key'].' is a duplicate in '.$jsonFile.' at line '.$details['line'];
}

Note: This library is meant to parse JSON while providing good error messages on failure. There is no way it can be as fast as php native json_decode().

It is recommended to parse with json_decode, and when it fails parse again with seld/jsonlint to get a proper error message back to the user. See for example how Composer uses this library:

Installation

For a quick install with Composer use:

$ composer require seld/jsonlint

JSON Lint can easily be used within another app if you have a PSR-4 autoloader, or it can be installed through Composer for use as a CLI util. Once installed via Composer you can run the following command to lint a json file or URL:

$ bin/jsonlint file.json

Requirements

  • PHP 5.3+
  • [optional] PHPUnit 3.5+ to execute the test suite (phpunit --version)

Submitting bugs and feature requests

Bugs and feature request are tracked on GitHub

Author

Jordi Boggiano - [email protected] - http://twitter.com/seldaek

License

JSON Lint is licensed under the MIT License - see the LICENSE file for details

Acknowledgements

This library is a port of the JavaScript jsonlint library.

GitHub

https://github.com/Seldaek/jsonlint
Comments
  • 1. Added optional support for duplicate keys

    Added support for duplicate keys via ALLOW_DUPLICATE_KEYS constant. Will take something like:

    {
        "a" : 1234,
        "a" : 4567,
        "a" : 8910
    }
    
    and convert to
    
    {
        "a" : 1234,
        "a.1" : 4567,
        "a.2" : 8910
    }
    

    In this way, if someone has a JSON file with keys that are acted like verbs, for example, for using JSON as configuration files, where you may have multiple action blocks. Rather than wrap blocks in extra brackets, or be forced to add unique charachters to verb.

    Reviewed by asnyder at 2012-11-30 20:22
  • 2. Build against PHP 7.0

    Composer fails from an exception of this library on PHP 7 so I enabled testing against PHP7 to see if unit tests pass. https://travis-ci.org/yiisoft/yii2/jobs/52251656#L1496

    Reviewed by cebe at 2015-02-26 13:38
  • 3. multibyte character sets are not supported

    $json = '{ "test": "Информация о балансе на договоре по номеру телефона: возвращает количество найденых договоров, баланс, блокировку, номер договора, тип договора, игнорим расторгнутые договора." }'; $parser = new JsonParser(); $parser->lint($json); $data = $parser->parse($json);

    Reviewed by aplab at 2014-04-02 04:02
  • 4. Massive performance problems with bigger JSON files

    Hey, we've just run into a major issue with jsonlint regarding performance today. Our requests were all timing out and stopped at the lexer. Here's a Sentry screenshot:

    image

    We've investigated the JSON that it tried to parse and while it was a bit bigger than usual, the parsing times were a LOT higher.

    So I've done some digging. The following numbers are for formatted JSON files:

    Lines (approx.) | execution time ---------|--------------- 10k | 1.89s user 0.03s system 96% cpu 1.989 total 25k | 6.29s user 0.05s system 98% cpu 6.419 total 40k | 25.82s user 13.47s system 99% cpu 39.521 total 50k | 58.24s user 43.51s system 99% cpu 1:42.27 total

    image (lines to time ratio)


    As it turns out, the library is actually waiting for the system to do its thing.

    A blackfire run with 3 samples on the 50k lines JSON shows that substr seems to be the culprit:

    image

    Due to privacy concerns I can't share the JSON file, but there should be random JSON generators out there that can create files for you.

    Many thanks in advance!

    Reviewed by spaceemotion at 2020-04-29 13:35
  • 5. Fix unicode characters handling

    Closes #59

    I'm not an expert at this so I'm not sure this is the best way to handle this case to be honest. It's also a bit weird to use json_decode there but I've picked that solution as alternatives suggested the use of mb_string and I preferred to avoid a dependency on an extension at this point.

    Reviewed by theofidry at 2019-10-23 07:10
  • 6. Don't ship tests and supporting files etc.

    I noticed that when installing this through composer the tests are also part of the package.

    Will you accept a PR to remove tests and supporting files from the distributions? If so, I will create one.

    I know not everyone likes that, hence I'm asking first.

    Reviewed by willemstuursma at 2020-05-20 09:17
  • 7. False negative when unquoted name/strings are passed in objects

    With the test json:

    { 	nonceValue:"90a9225e1ac785aea7c9e80f232d21a6" }
    

    (yep, just that)

    PHP's own json_decode returns Syntax error, it looks like Github's markdown display system also detects the issue, and https://jsonlint.com/ returns

    Error: Parse error on line 1:
    {	nonceValue: "90a9225
    --^
    Expecting 'STRING', '}', got 'undefined'
    

    However, the linter (release 1.7) fails to detect an issue.

    Reviewed by rbairwell at 2019-08-07 09:28
  • 8. Weird parsing of unicode characters

    Given the following JSON:

    {
      "errors": [
        {
          "message": "Argument \u0022input\u0022 has an invalid value: ...."
        }
      ]
    }
    

    (for some reason a mink driver is returning this instead of \"...)

    With json_decode() you will get:

    {#4
      +"errors": array:1 [
        0 => {#5
          +"message": "Argument "input" has an invalid value: ...."
        }
      ]
    }
    

    However with JsonParser you will get:

    {#17
      +"errors": array:1 [
        0 => {#16
          +"message": "Argument "input" has an invalid value: ...."
        }
      ]
    }
    

    Any idea of how this could be fixed?

    Reviewed by theofidry at 2019-08-05 14:36
  • 9. error for bad backslashes gives unrelated error message with the wrong location

    Given the following JSON:

    {
      "SA-CORE-2019-002": "../patches/sa-core-2019-002.patch",
      "#3026386-26 - Drush fatal error after upgrading to 8.6.6, 8.5.9, or 7.62: PHP Fatal error: Uncaught TYPO3\PharStreamWrapper\Exception": "https://www.drupal.org/files/issues/2019-01-16/d8-3026386-26.patch"
    }
    

    the error is:

    test.json: Parse error on line 2:
    ...-2019-002.patch",  "#3026386-26 - Drush
    ---------------------^
    Invalid string, it appears you forgot to terminate a string, or attempted to write a multiline string which is invalid - It appears you have an extra trailing comma
    

    The error message doesn't seem related, as there is no extra trailing comma.

    Reviewed by joachim-n at 2019-01-18 13:33
  • 10. Does it support PHP 7.1 and 7.2 too?

    Hi! I guess your code does support. :) I just see some limitations in composer.json file. Could you test your code and update requirements?

    Thanks for the module, by the way!

    Reviewed by andkirby at 2018-07-04 15:03
  • 11. added cli support for multiple file arguments

    Added support for multiple JSON files to be passed as arguments to jsonlint cli utility

    Basic usage: ./vendor/bin/jsonlint file.json otherFile.json

    Advanced usage: ./vendor/bin/jsonlint $(find . -type f -iname "*.json" -printf "%p ")

    Output example: ./jsonlint file.json otherFIle.json Checking 2 files Valid JSON (file.json) Valid JSON (otherFIle.json)

    Reviewed by jackgleeson at 2017-12-22 13:12
PHP Parallel Lint - This tool check syntax of PHP files faster than serial check with fancier output
PHP Parallel Lint - This tool check syntax of PHP files faster than serial check with fancier output

PHP Parallel Lint This application checks syntax of PHP files in parallel. It can output in plain text, colored text, json and checksyntax formats. Ad

Apr 24, 2022
Allows generate class files parse from json and map json to php object, including multi-level and complex objects;

nixihz/php-object Allows generate class files parse from json and map json to php object, including multi-level and complex objects; Installation You

Oct 29, 2021
Json-normalizer: Provides generic and vendor-specific normalizers for normalizing JSON documents

json-normalizer Provides generic and vendor-specific normalizers for normalizing JSON documents. Installation Run $ composer require ergebnis/json-nor

Jan 16, 2022
Zilliqa PHP is a typed PHP-7.1+ interface to Zilliqa JSON-RPC API.
Zilliqa PHP is a typed PHP-7.1+ interface to Zilliqa JSON-RPC API.

Zilliqa PHP is a typed PHP-7.1+ interface to Zilliqa JSON-RPC API. Check out the latest API documentation. Add library in a composer.json file.

Oct 7, 2021
Php-rpc-server - JSON RPC server implementation for PHP.

JSON RPC Server implementation for PHP. The json-rpc is a very simple protocol. You can see this by reading the protocol specification. This library i

Mar 8, 2022
Simple game server with php without socket programming. Uses the Api request post(json).

QMA server Simple game server with php without socket programming. Uses the Api request post(json). What does this code do? Register the user as a gue

Sep 4, 2021
Learning about - Basic HTML & CSS, JSON, XML, Session & Cookies, CRUD Operations in Php using MySQL and Create MVC from scratch
 Learning about - Basic HTML & CSS, JSON, XML, Session & Cookies, CRUD Operations in Php using MySQL and Create MVC from scratch

This Project is based on course CSC 3215. Learning about - Basic HTML & CSS, JSON, XML, Session & Cookies, CRUD Operations in Php using MySQL and Create MVC (Model–View–Controller) from scratch. Just learning about web technologies, Not focusing on UI (Bootstrap or other 3rd-Party UI libraries or frameworks).

Apr 16, 2022
Declaratively specify how to extract elements from a JSON document, in PHP

jmespath.php JMESPath (pronounced "jaymz path") allows you to declaratively specify how to extract elements from a JSON document. jmespath.php allows

May 19, 2022
Dependency graph visualization for composer.json (PHP + Composer)
Dependency graph visualization for composer.json (PHP + Composer)

clue/graph-composer Graph visualization for your project's composer.json and its dependencies: Table of contents Usage graph-composer show graph-compo

May 18, 2022
JsonQ is a simple, elegant PHP package to Query over any type of JSON Data

php-jsonq JsonQ is a simple, elegant PHP package to Query over any type of JSON Data. It'll make your life easier by giving the flavour of an ORM-like

May 4, 2022
The main website source code based on php , html/css/js and an independent db system using xml/json.
The main website source code based on php , html/css/js and an independent db system using xml/json.

jsm33t.com Well umm, a neat website LIVE SITE » View Demo · Report Bug · Request a feature About The Project Desc.. Built Using Php UI Frameworks Boot

May 3, 2022
This is a library to serialize PHP variables in JSON format

This is a library to serialize PHP variables in JSON format. It is similar of the serialize() function in PHP, but the output is a string JSON encoded. You can also unserialize the JSON generated by this tool and have you PHP content back.

Feb 12, 2022
Swaggest JSON-schema implementation for PHP

Swaggest JSON-schema implementation for PHP High definition PHP structures with JSON-schema based validation. Supported schemas: JSON Schema Draft 7 J

May 17, 2022
The easiest way to match data structures like JSON/PlainText/XML against readable patterns. Sandbox:

PHP Matcher Library created for testing all kinds of JSON/XML/TXT/Scalar values against patterns. API: PHPMatcher::match($value = '{"foo": "bar"}', $p

May 24, 2022
It's MX Player API gives All Content in JSON format

?? MXPlayer API ?? ?? MXPlayer API Can get Streaming URLs and Other Data in JSON Format From mxplayer.in links for Streaming ?? How to Use : ?? Method

Nov 30, 2021
JSON schema models and generated code to validate and handle various data in PocketMine-MP

DataModels JSON schema models and generated code to validate and handle various data in PocketMine-MP This library uses php-json-schema-model-generato

Nov 17, 2021
Simple user settings facade for Hyperf. Settings are stored as JSON in a single database column, so you can easily add it to an existing table.

hyperf-user-settings Simple user settings util for hyperf Settings are stored as JSON in a single database column, so you can easily add it to an exis

Oct 15, 2021
Here is an Instagram Guest API. Gather all public information as JSON format without logging yourself.

Here is an Instagram Guest API. Gather all public information as JSON format without logging yourself. It's all automation and time saving.

Nov 2, 2021
A Magento implementation for validating JSON Structures against a given Schema

Zepgram JsonSchema A Magento implementation for validating JSON Structures against a given Schema with support for Schemas of Draft-3 or Draft-4. Base

Nov 5, 2021