如何确定字符串是否为有效的JSON? [英] How to determine whether a string is valid JSON?

查看:160
本文介绍了如何确定字符串是否为有效的JSON?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人知道PHP的健壮(和防弹)is_JSON函数代码片段吗?我(显然)遇到一种情况,我需要知道字符串是否为JSON.

嗯,也许通过 JSONLint 请求/响应来运行它,但这似乎有些过分.

解决方案

如果您使用的是内置的 json_decode PHP函数, json_last_error 返回最后一个错误(例如 JSON_ERROR_SYNTAX (当您的字符串不是JSON时).

通常 json_decode 始终返回null.

Does anyone know of a robust (and bullet proof) is_JSON function snippet for PHP? I (obviously) have a situation where I need to know if a string is JSON or not.

Hmm, perhaps run it through a JSONLint request/response, but that seems a bit overkill.

解决方案

If you are using the built in json_decode PHP function, json_last_error returns the last error (e.g. JSON_ERROR_SYNTAX when your string wasn't JSON).

Usually json_decode returns null anyway.

这篇关于如何确定字符串是否为有效的JSON?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆