【问题标题】:Use of if (typeof(obj._source.url) !== 'undefined') expresion in jsontohtml在 json 到 html 中使用 if (typeof(obj._source.url) !== 'undefined') 表达式
【发布时间】:2020-08-14 21:06:19
【问题描述】:

我正在咨询两个不同的 json 数据源,job1 和 job2,使用与 jsontohtml 运行的相同代码。

每个来源都有不同的标签,虽然名称相似,但有些名称不同或不同的json结构。

我想检测何时定义了标签以在 html 中显示它,而如果未定义则不显示它。

问题是当我检查下一个命令是否已经定义了相应的参数对象时

if (typeof(obj._source.file.url) !== 'undefined')

我收到以下错误

Uncaught TypeError: Cannot read property 'url' of undefined

完整的代码是

<html>
<head>
    <meta charset='UTF-8' />
    <title>JSON Visualizer</title>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/json2html/1.4.0/json2html.min.js"></script>
</head>

<link rel="stylesheet" href="./tablaX.css">

<body>

    <div class="container">
        <div class="table-responsive">
            <div id="elastic_table">            
            </div>
        </div>
    </div>

<script type="text/javascript"> 
$(document).ready(function(){

        var trabajo = "job2";
        var url = 'http://localhost:9200/' + trabajo + '/_search'

        let transforms = {  "response":
                        {'<>':'table','class':'table-bordered table-striped table-hover results','html':[

                        {'<>':'thead'},     

                        {'<>':'tr'},
                        {'<>':'th','text':'URL'},


                        {'<>':'tbody'},     

                        {"<>":"div","html":function() {
                                return($.json2html(this.hits.hits,transforms.hitos));
                            }}

                        ]},                 

                        "hitos":{"<>":"tr","html":[

                            {"<>":"td","html":function(obj,index){
                                if (typeof(obj._source.file.url) !== 'undefined') { http = obj._source.file.url.replace("file://", ""); return("<a href='" + http + "'>" + http + "</a>"); };    //job 1 source
                                if (typeof(obj._source.url) !== 'undefined') { http = obj._source.url.replace("file://", ""); return("<a href='" + http + "'>" + http + "</a>"); };      //job 2 source                 

                                }
                                }

                        ]}              

                    };

                    var datos = 
                    {   
                        "query": {
                            "match_all": {}
                                 },
                        "size": "10000"
                    }
                    ;               


         [datos].map(function (query) {
          $.ajax({
            url,
            type: "post",
            data: JSON.stringify(query),
            contentType: "application/json",
            dataType: "json",
            success: function (responses) {
              console.log({ query, responses });
              $('#elastic_table').html(json2html.transform(responses,transforms.response));
            },
            error: function (err) {
              console.error({ query, err });
            }
          });
        });



        }
    )   
;      

</script>
</body>
</html>

如果您注释下一行的代码,这是给我错误的代码,我的 jsontohtml 代码将毫无问题地工作

if (typeof(obj._source.file.url) !== 'undefined') { http = obj._source.file.url.replace("file://", ""); return("<a href='" + http + "'>" + http + "</a>"); };    //job 1 source

源job1的源数据是

{
  "took" : 0,
  "timed_out" : false,
  "_shards" : {
    "total" : 1,
    "successful" : 1,
    "skipped" : 0,
    "failed" : 0
  },
  "hits" : {
    "total" : {
      "value" : 5,
      "relation" : "eq"
    },
    "max_score" : 1.0,
    "hits" : [
      {
        "_index" : "job1",
        "_type" : "_doc",
        "_id" : "2e2ed07786c01e9fd845b62fb86a693a",
        "_score" : 1.0,
        "_source" : {
          "content" : """hola
""",
          "meta" : { },
          "file" : {
            "extension" : "txt",
            "content_type" : "text/plain; charset=ISO-8859-1",
            "created" : "2020-04-03T11:57:45.673+0000",
            "last_modified" : "2020-04-23T07:33:50.725+0000",
            "last_accessed" : "2020-04-23T07:33:50.725+0000",
            "indexing_date" : "2020-04-23T10:33:46.954+0000",
            "filesize" : 4,
            "filename" : "fichero0_borrador.txt",
            "url" : """file://C:\TMPM\carpeta0\99.Borrador\fichero0_borrador.txt"""
          },
          "path" : {
            "root" : "4cface21f575d5e5985e4e3889c278a3",
            "virtual" : "PM/carpeta0/99.Borrador/fichero0_borrador.txt",
            "real" : """C:\TMPM\carpeta0\99.Borrador\fichero0_borrador.txt"""
          }
        }
      },
      {
        "_index" : "job1",
        "_type" : "_doc",
        "_id" : "6f475ff7ac21fc59f4edc34761d09",
        "_score" : 1.0,
        "_source" : {
          "content" : """cadena0 A
""",
          "meta" : { },
          "file" : {
            "extension" : "txt",
            "content_type" : "text/plain; charset=ISO-8859-1",
            "created" : "2020-04-14T09:30:20.218+0000",
            "last_modified" : "2020-04-14T09:46:02.930+0000",
            "last_accessed" : "2020-04-14T09:46:02.930+0000",
            "indexing_date" : "2020-04-23T10:33:47.533+0000",
            "filesize" : 9,
            "filename" : "fichero0_A.txt",
            "url" : """file://C:\TMPM\carpeta0\fichero0_A.txt"""
          },
          "path" : {
            "root" : "c073f96a8d16ebb2e604bebd4fe8b40",
            "virtual" : "PM/carpeta0/fichero0_A.txt",
            "real" : """C:\TMPM\carpeta0\fichero0_A.txt"""
          }
        }
      },
      {
        "_index" : "job1",
        "_type" : "_doc",
        "_id" : "7dfb102f2e64e99740a89b1cff7d92a3",
        "_score" : 1.0,
        "_source" : {
          "content" : """cadena1
""",
          "meta" : { },
          "file" : {
            "extension" : "txt",
            "content_type" : "text/plain; charset=ISO-8859-1",
            "created" : "2020-04-03T11:56:21.165+0000",
            "last_modified" : "2020-04-03T12:23:23.872+0000",
            "last_accessed" : "2020-04-03T12:23:23.872+0000",
            "indexing_date" : "2020-04-23T10:33:47.568+0000",
            "filesize" : 7,
            "filename" : "fichero1.txt",
            "url" : """file://C:\TMPM\carpeta1\fichero1.txt"""
          },
          "path" : {
            "root" : "7ff4e7b0e0c3172dbd29a23861ab2125",
            "virtual" : "PM/carpeta1/fichero1.txt",
            "real" : """C:\TMPM\carpeta1\fichero1.txt"""
          }
        }
      },
      {
        "_index" : "job1",
        "_type" : "_doc",
        "_id" : "74f0e8c1cccf2f32b4d43673cfdca0",
        "_score" : 1.0,
        "_source" : {
          "content" : """cadena2
""",
          "meta" : { },
          "file" : {
            "extension" : "txt",
            "content_type" : "text/plain; charset=ISO-8859-1",
            "created" : "2020-04-03T11:56:30.524+0000",
            "last_modified" : "2020-04-03T12:23:35.029+0000",
            "last_accessed" : "2020-04-03T12:23:35.029+0000",
            "indexing_date" : "2020-04-23T10:33:47.579+0000",
            "filesize" : 7,
            "filename" : "fichero2.txt",
            "url" : """file://C:\TMPM\carpeta2\fichero2.txt"""
          },
          "path" : {
            "root" : "fd0c8ae8a885725cfcaee774c72be43",
            "virtual" : "PM/carpeta2/fichero2.txt",
            "real" : """C:\TMPM\carpeta2\fichero2.txt"""
          }
        }
      },
      {
        "_index" : "job1",
        "_type" : "_doc",
        "_id" : "8d6c56c0448bc4bfa17787923baa9c",
        "_score" : 1.0,
        "_source" : {
          "content" : """cadenaX
""",
          "meta" : { },
          "file" : {
            "extension" : "txt",
            "content_type" : "text/plain; charset=ISO-8859-1",
            "created" : "2020-04-14T15:12:56.632+0000",
            "last_modified" : "2020-04-14T15:34:53.139+0000",
            "last_accessed" : "2020-04-14T15:34:53.139+0000",
            "indexing_date" : "2020-04-23T10:33:47.587+0000",
            "filesize" : 7,
            "filename" : "fichero_X.txt",
            "url" : """file://C:\TMPM\carpetaX\fichero_X.txt"""
          },
          "path" : {
            "root" : "f43118a935c6c7ef81ea65307759fc",
            "virtual" : "PM/carpetaX/fichero_X.txt",
            "real" : """C:\TMPM\carpetaX\fichero_X.txt"""
          }
        }
      }
    ]
  }
}


提前致谢

【问题讨论】:

  • 一,typeof不是函数,所以typeof something而不是typeof(something)。二,它告诉你file在这里是未定义的:obj._source.file你不能从未定义中获取属性。

标签: javascript json2html


【解决方案1】:

根据错误file 在obj._source.file.url 中未定义。试试

if (typeof obj._source.file !== 'undefined') { 
    if (typeof obj._source.file.url !== 'undefined') {
        http = obj._source.file.url.replace("file://", ""); return("<a href='" + http + "'>" + http + "</a>"); 
    };
};    //job 1 source 

【讨论】:

  • 从那里您应该能够使用简单的 else 语句进行验证并从那里开始。
  • if (obj &amp;&amp; obj._source &amp;&amp; obj._source.file &amp;&amp; obj._source.file.url) {...}
  • 我还在developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… 测试了 typeof() 并且它与括号一起使用。不好的做法,但这不是你的紧迫问题。
  • 这不是坏习惯,而是一种奇怪的做法。考虑一下以下内容本身实际上都不是“错误的”:(a =&gt; { return(a &amp;&amp;(true &amp;&amp;(10 &amp;&amp;(false))) ||(typeof(1.444) === 'float' ))})(1) parans 是对表达式的分组,因此它们是合法的,但没有必要。
【解决方案2】:

我添加的代码是我完成的众多测试之一,其中我留下了著名的不正确括号。我知道我将在未声明和未定义状态下找到我的对象obj._source.file。正是因为它将接收到的json会改变它的定义和结构(它是几个json的混合)。正因为如此,我使用了typeof obj._source.file! == 'undefined',因为谷歌回复“使用 typeof 运算符:如果你想检查一个变量是否已经被初始化或定义(即测试一个变量是否已经被声明并赋值)你可以使用 typeof 操作符。”

终于用上了

 if (obj && obj._source && obj._source.file && obj._source.file.url) {...} 

Jared Farrish 取得了不错的成绩。谢谢

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    相关资源
    最近更新 更多