简体   繁体   中英

Filtering JSON reply in jQuery

I'm attempting to filter out the reply I get from a JSON query to the 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. I basically just want to display each meaning on a line of it's own.

jquery code:

$(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:

<!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. You can use it to send JavaScript objects around. You should take advantage of this, not flatten it and mess with string parsing.

Your json variable contains something like this:

{
...
"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"] ; each of those contains an array of meanings (ie json["tuc"][0]["meanings"] ). You can loop through each of those and extract the text property to build up your output.

For example, inside .getJSON , once you've verified that you do have data:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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