如何使用PHP解码带注释的JSON文件? [英] How can I decode JSON files with comments using PHP?

查看:63
本文介绍了如何使用PHP解码带注释的JSON文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在一项任务中,我必须在 JSON 文件中编写注释,然后使用 PHP 对其进行解码.我分享.也许它可以帮助别人.正则表达式很难.

In a task I had to write comments in JSON files and decode them using PHP. I share it. Maybe it helps someone else. The regex was tough.

推荐答案

使用正则表达式删除注释

$jsonStringWithComments = file_get_contents ( "jsonFileWithComments.json" );
$pattern = '/(((?<!http:|https:)\/\/.*|(\/\*)([\S\s]*?)(\*\/)))/im';
$decodedObject = json_decode ( preg_replace ( $pattern, '', $jsonStringWithComments ) );

此正则表达式可以捕获单行"注释,在斜杠星号/*和星号斜杠*/之间以双斜杠//或多行"注释.

This regular expression can capture "one-line" comments, start double slashes // or "multi-line" comments between slash asterisk /* and asterisk slash */.

有了它,您可以像下面那样解析JSON:

With it, you can parse JSON like the following:

{
  "lorem": "ipsum",
  "dolor":/* inline comment */ "sit amet",
  "consectetur": "adipiscing",
/*
multi
line
comment
*/  
  "Pellentesque": "ultrices",
//single line comment  
  "lectus": "nec",
  "elit": "dictum",
  "url": "http://example.com"
}

这篇关于如何使用PHP解码带注释的JSON文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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