正则表达式来验证 JSON [英] Regex to validate JSON

查看:59
本文介绍了正则表达式来验证 JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找允许我验证 json 的正则表达式.

I am looking for a Regex that allows me to validate json.

我对 Regex 很陌生,我很清楚用 Regex 解析很糟糕,但它可以用来验证吗?

I am very new to Regex's and i know enough that parsing with Regex is bad but can it be used to validate?

推荐答案

是的,可以进行完整的正则表达式验证.

大多数现代正则表达式实现都允许递归正则表达式,它可以验证完整的 JSON 序列化结构.json.org 规范 使它变得非常简单.

$pcre_regex = '
  /
  (?(DEFINE)
     (?<number>   -? (?= [1-9]|0(?!d) ) d+ (.d+)? ([eE] [+-]? d+)? )    
     (?<boolean>   true | false | null )
     (?<string>    " ([^"\\]* | \\ ["\\bfnrt/] | \\ u [0-9a-f]{4} )* " )
     (?<array>     [  (?:  (?&json)  (?: , (?&json)  )*  )?  s* ] )
     (?<pair>      s* (?&string) s* : (?&json)  )
     (?<object>    {  (?:  (?&pair)  (?: , (?&pair)  )*  )?  s* } )
     (?<json>   s* (?: (?&number) | (?&boolean) | (?&string) | (?&array) | (?&object) ) s* )
  )
  A (?&json) 
  /six   
';

在 PHP 中使用 PCRE 函数 时效果很好.应该在 Perl 中未经修改地工作;并且当然可以适用于其他语言.它也通过 JSON 测试用例成功.

It works quite well in PHP with the PCRE functions . Should work unmodified in Perl; and can certainly be adapted for other languages. Also it succeeds with the JSON test cases.

一种更简单的方法是在 RFC4627 第 6 节中指定的最小一致性检查.然而,它只是作为安全测试和基本的非有效性预防措施:

A simpler approach is the minimal consistency check as specified in RFC4627, section 6. It's however just intended as security test and basic non-validity precaution:

  var my_JSON_object = !(/[^,:{}[]0-9.-+Eaeflnr-u 

	]/.test(
         text.replace(/"(\.|[^"\])*"/g, ''))) &&
     eval('(' + text + ')');

这篇关于正则表达式来验证 JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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