JSON Lint for PHP

Overview

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.

Comments
  • Added optional support for duplicate keys

    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.

    opened by asnyder 10
  • Build against PHP 7.0

    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

    opened by cebe 9
  • multibyte character sets are not supported

    multibyte character sets are not supported

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

    opened by aplab 7
  • Massive performance problems with bigger JSON files

    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!

    opened by spaceemotion 5
  • Fix unicode characters handling

    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.

    opened by theofidry 5
  • Don't ship tests and supporting files etc.

    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.

    opened by willemstuursma 3
  • False negative when unquoted name/strings are passed in objects

    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.

    opened by rbairwell 3
  • Weird parsing of unicode characters

    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?

    opened by theofidry 3
  • error for bad backslashes gives unrelated error message with the wrong location

    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.

    opened by joachim-n 3
  • Does it support PHP 7.1 and 7.2 too?

    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!

    opened by andkirby 3
  • added cli support for multiple file arguments

    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)

    opened by jackgleeson 3
Releases(1.9.0)
Owner
Jordi Boggiano
Working on https://packagist.com and https://teamup.com - @composer lead - OSS wishlist: https://seld.be/wishlist
Jordi Boggiano
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

PHP Parallel lint 156 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

zhixin 2 Sep 9, 2022
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

null 64 Dec 31, 2022
PDF API. JSON to PDF. PDF Template Management, Visual HTML Template Editor and API to render PDFS by json data

PDF Template Management, Visual HTML Template Editor and API to render PDFS by json data PDF ENGINE VERSION: development: This is a prerelease version

Ajous Solutions 2 Dec 30, 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. Check out the latest API documentation. Add library in a composer.json file.

Patrick Falize 6 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

null 4 Sep 28, 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

reza malekpour 3 Sep 4, 2021
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).

Alvi Hasan 5 Sep 21, 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

null 1.7k Dec 30, 2022
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

Christian Lück 797 Jan 5, 2023
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

Nahid Bin Azhar 834 Dec 25, 2022
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

Jasmeet Singh 5 Nov 23, 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.

Zumba 118 Dec 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

null 370 Dec 29, 2022
World countries - available in multiple languages, in CSV, JSON, PHP, SQL and XML formats

Constantly updated lists of world countries and their associated alpha-2, alpha-3 and numeric country codes as defined by the ISO 3166 standard, available in CSV, JSON , PHP, SQL and XML formats, in multiple languages and with national flags included; also available are the ISO 3166-2 codes of provinces/ states associated with the countries

Stefan Gabos 1k Dec 29, 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

Coduo 774 Dec 31, 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

Techie Sneh 8 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

PMMP 2 Nov 9, 2022
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

lysice 1 Oct 15, 2021