我可以在json文件里使用注释吗? 如果是的话,怎么写?


当前回答

*.json文件通常用作配置文件或静态数据,因此需要评论 * 一些像Netbeans这样的编辑在 *.json中接受评论。

问题在于将内容解析到对象上。 解决办法是总是应用清洁功能( 服务器或客户端 ) 。

php /p

 $rgx_arr = ["/\/\/[^\n]*/sim", "/\/\*.*?\*\//sim", "/[\n\r\t]/sim"];
 $valid_json_str = \preg_replace($rgx_arr, '', file_get_contents(path . 'a_file.json'));

手笔

valid_json_str = json_str.replace(/\/\/[^\n]*/gim,'').replace(/\/\*.*?\*\//gim,'')

其他回答

i 只是为配置文件遇到这种情况。 我不想使用 xml (verbose, 图形化, 丑陋, 难以阅读) 或“ ini” 格式( 没有等级, 没有真正的标准等) 或 java “ properities” 格式( 如. ini) 。

json可以做他们所能做的一切, 但它的动词要少得多,更易人读—— 剖析器在许多语言中是简单易懂的和无处不在的。 它只是一棵数据树。 但是外带评论往往需要记录“ 默认” 配置和类似内容。 配置从来不是“ 完整的文档 ” , 但需要时保存的数据的树可以被人类读取。

我猜有人可以用"":"评论"来形容"有效"json"

在json中不允许使用表格///...或/*...* /的注释。

https://www.json.org rfc 4627: Javacampn 对象标记(json)申请/json媒体类型(json) rfc 8259; json) 数据交换格式(supercedes rfcs 4627, 7158, 7159)

在我目前的项目中,我遇到了这个问题, 因为我有相当多的json 需要一些评论 使事情容易记住。

i've used this simple python 函数来替换批注并使用 json. loads 将其转换成 dict:

import json, re

def parse_json(data_string):
  result = []
  for line in data_string.split("\n"):
    line = line.strip()
    if len(line) < 1 or line[0:2] == "//":
      continue
    if line[-1] not in "\,\"\'":
      line = re.sub("\/\/.*?$", "", line)
    result.append(line)
  return json.loads("\n".join(result))

print(parse_json("""
{
  // This is a comment
  "name": "value" // so is this
  // "name": "value"
  // the above line gets removed
}
"""))

(hack)是一个很好的解决办法(hack),这是有效的json,但并非在所有情况下都能奏效(见下文的评论)。

{
  "param" : "This is the comment place",
  "param" : "This is value place",
}

所以json会理解这一点:

{
  "param" : "This is value place",
}

*.json文件通常用作配置文件或静态数据,因此需要评论 * 一些像Netbeans这样的编辑在 *.json中接受评论。

问题在于将内容解析到对象上。 解决办法是总是应用清洁功能( 服务器或客户端 ) 。

php /p

 $rgx_arr = ["/\/\/[^\n]*/sim", "/\/\*.*?\*\//sim", "/[\n\r\t]/sim"];
 $valid_json_str = \preg_replace($rgx_arr, '', file_get_contents(path . 'a_file.json'));

手笔

valid_json_str = json_str.replace(/\/\/[^\n]*/gim,'').replace(/\/\*.*?\*\//gim,'')