DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Refcards Trend Reports Events Over 2 million developers have joined DZone. Join Today! Thanks for visiting DZone today,
Edit Profile Manage Email Subscriptions Moderation Admin Console How to Post to DZone Article Submission Guidelines
View Profile
Sign Out
Refcards
Trend Reports
Events
Zones
Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones AWS Cloud
by AWS Developer Relations
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Partner Zones
AWS Cloud
by AWS Developer Relations
Securing Your Software Supply Chain with JFrog and Azure
Register Today

Trending

  • Front-End: Cache Strategies You Should Know
  • Step Into Serverless Computing
  • Mastering Go-Templates in Ansible With Jinja2
  • SRE vs. DevOps

Trending

  • Front-End: Cache Strategies You Should Know
  • Step Into Serverless Computing
  • Mastering Go-Templates in Ansible With Jinja2
  • SRE vs. DevOps
  1. DZone
  2. Data Engineering
  3. Data
  4. Handing JSON Data Errors in Slim 3

Handing JSON Data Errors in Slim 3

Rob Allen shows us how to handle JSON data errors in Slim 3.

Rob Allen user avatar by
Rob Allen
·
Nov. 28, 16 · Tutorial
Like (0)
Save
Tweet
Share
5.77K Views

Join the DZone community and get the full member experience.

Join For Free

When you send JSON data into a Slim Framework application with a content-type of application/json, then Slim will decode it for you if you use getParsedBody():

$app->post("/", function ($request, $response, $args) {
    $input = $request->getParsedBody();

    var_dump($input);exit;
});

Using curl to test:

$ curl -H "Content-Type: application/json" http://localhost:8888 -d '{"foo": "bar"}'
array(1) {
  'foo' =>
  string(3) "bar"
}

If there's an error however, you get this:

$ curl -H "Content-Type: application/json" http://localhost:8888 -d '{foo: bar}'
NULL

If you care about this, you can use json_last_error_msg() and return an error:

$app->post("/", function ($request, $response, $args) {
    $input = $request->getParsedBody();
    if ($input === null) {
        return $response->withJson(
            ['error_decoding_json' => json_last_error_msg()],
            400,
            JSON_PRETTY_PRINT
        );
    }

    var_dump($input);exit;
});

(note – in real code, you should check that the Accept header was a JSON one…)

Don't forget the JSON_PRETTY_PRINT as a human is going to be reading this error, so make it easier for them.

Use jsonlint for More Information

If you really want to provide great diagnostics, then use jsonlint:

$ composer require seld/jsonlint

Update your handler like this:

$app->post("/", function ($request, $response, $args) {
    $input = $request->getParsedBody();
    if ($input === null) {
        $parser = new \Seld\JsonLint\JsonParser();
        $result = $parser->lint($input);
        if ($result instanceof \Seld\JsonLint\ParsingException) {
            return $response->withJson(
                ['error_decoding_json' => $result->getMessage()],
                400,
                JSON_PRETTY_PRINT
            );
        }
    }

    var_dump($input);exit;
});

(lint() will return NULL or a ParsingException, so we don't need to test for anything else.)

The result looks like this:

$ curl -H "Content-Type: application/json" http://localhost:8888 -d '{foo: bar}'
{
    "error_decoding_json": "Parse error on line 1:\n\n^\nExpected one of: 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['"
}

This is much more informative!

JSON Data (computing)

Published at DZone with permission of Rob Allen, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Trending

  • Front-End: Cache Strategies You Should Know
  • Step Into Serverless Computing
  • Mastering Go-Templates in Ansible With Jinja2
  • SRE vs. DevOps

Comments

Partner Resources

X

ABOUT US

  • About DZone
  • Send feedback
  • Careers
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 600 Park Offices Drive
  • Suite 300
  • Durham, NC 27709
  • support@dzone.com

Let's be friends: