简体   繁体   English

在jQuery中过滤JSON回复

[英]Filtering JSON reply in jQuery

I'm attempting to filter out the reply I get from a JSON query to the Glosbe.com API. 我正在尝试过滤掉从JSON查询到Glosbe.com API的答复。

Currently I've been able to break the JSON down to only receive the meanings but I'm unsure how to remove all of the commas and other aspects of the JSON response. 目前,我已经能够将JSON分解为仅接收含义,但是我不确定如何删除JSON响应的所有逗号和其他方面。 I basically just want to display each meaning on a line of it's own. 我基本上只想在一行上显示每个含义。

jquery code: jQuery代码:

$(document).ready(function(){

$('#term').focus(function(){
var full = $("#definition").has("definition").length ? true : false;
if(full === false){
 $('#definition').empty();
 }
});

var getDefinition = function(){

 var word = $('#term').val();

  if(word === ''){

    $('#definition').html("<h2 class='loading'>We haven't forgotten to validate the form! Please enter a word.</h2>");

  } 

   else {

    $('#definition').html("<h2 class='loading'>Your definition is on its way!</h2>");

    $.getJSON("http://glosbe.com/gapi/translate?from=eng&dest=eng&format=json&phrase=" +word+ "&pretty=true&callback=?", function(json) {

       if (json !== "No definition has been found."){

           var reply = JSON.stringify(json,null,"\t");
           var n = reply.indexOf("meanings");
           var sub = reply.substring(n+8,reply.length);
           var subn = sub.indexOf("]");
           sub = sub.substring(0,subn);

             $('#definition').html('<h2 class="loading">We found you a definition!</h2>  <h3>'+sub+'</h3>');

          } 

else {
             $.getJSON("http://glosbe.com/gapi/translate?from=eng&dest=rus&format=json&phrase=&pretty=true" + "?callback=?", function(json) {
                console.log(json);
                $('#definition').html('<h2 class="loading">Nothing found.</h2><img   id="thedefinition" src=' + json.definition[0].image.url + ' />');
             });
          }
     });

  }

return false;
};

$('#search').click(getDefinition);
$('#term').keyup(function(event){
if(event.keyCode === 13){
   getDefinition();
}
});

});

HTML page: HTML页面:

<!DOCTYPE html>
<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta name="author" content="Matthew Hughes">
<title>Dictionary Web Application</title>
<script src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.2.min.js"></script>
<script src="dictionary.js"></script>
<link rel="stylesheet" href="style.css" />

</head>

<body>

<div id="container">
    <header>
        <h1>Dictionary Application</h1>
    </header>
    <section id="fetch">
        <input type="text" placeholder="Enter a word..." id="term" />
        <button id="search">Define!</button>
    </section>
    <section id="definition">
    </section>
    <footer>
        <p>Created by Matthew & Spencer</p>
    </footer>
</div>

Thanks. 谢谢。

JSON is JavaScript Object Notation. JSON是JavaScript对象表示法。 You can use it to send JavaScript objects around. 您可以使用它来发送JavaScript对象。 You should take advantage of this, not flatten it and mess with string parsing. 您应该利用此优势,而不是将其弄平并弄乱字符串解析。

Your json variable contains something like this: 您的json变量包含以下内容:

{
...
"tuc": [
    {
        "authors": [
            1
        ],
        "meaningId": null,
        "meanings": [
            {
                "language": "eng",
                "text": "The process of applying a test as a means of analysis or diagnosis."
            },
            {
                "language": "eng",
                "text": "difficult, tough"
            },
            {
                "language": "eng",
                "text": "Present participle of test."
            },
            {
                "language": "eng",
                "text": "The act of conducting a test; trialing, proving"
            }
        ]
    },
    ...
    ]
    }

You can access the section with the meanings with json["tuc"] ; 您可以使用json["tuc"]访问具有含义的部分; each of those contains an array of meanings (ie json["tuc"][0]["meanings"] ). 每个都包含一个意义数组(即json["tuc"][0]["meanings"] )。 You can loop through each of those and extract the text property to build up your output. 您可以遍历所有这些内容并提取text属性以构建您的输出。

For example, inside .getJSON , once you've verified that you do have data: 例如,在.getJSON内部,一旦您确认确实有数据:

    var meanings = "";
    json["tuc"].forEach(function(tuc) {
        tuc["meanings"].forEach(function(m) {
            meanings += "<p>"+m["text"]+"</p>\n";
        });
    });
    $("#definition").html(meanings);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM