DataGuy
DataGuy

Reputation: 1725

Parsing JSON Data/Converting to Objects

I am using the following function as a test case for my application:

$(function() {
var json = {
    "people": {
        "person": [{
            "name": "Peter",
            "age": 43,
            "sex": "male"},
        {
            "name": "Zara",
            "age": 65,
            "sex": "female"}]
    }
};
$.each(json.people.person, function(i, v) {
    if (v.name == "Peter") {
        alert(v.age);
        return;
    }
});
});

This simply searches a set of JSON data for a static input, which in this case is the name "Peter", and returns his 'age'. I want to modify this function to pull input from a text field and use it in place of the static string "Peter" so I can search for any name Id like. The function will be called from a submit button.

That is my first obstacle.

My second is Id like to use the subset of the result as an object, rather than a string, in my application. In other words, if I placed a name in a text field the function would find the name within the JSON data and return, in this case, 'age' as an object that I can then use for other calculations in the work flow.

Can anyone help me with this?

Thanks!

Upvotes: 0

Views: 79

Answers (2)

Mihnea Belcin
Mihnea Belcin

Reputation: 554

i made a fiddle that makes what you need http://jsfiddle.net/KmYJw/1/

lets say you have 2 form fields . 1 text & 1 submit

<input name="name" value="" type="text" />
<input value="search in json" type="submit" />

when you click submit . you need to take the value from the text input and search for in in the json

    var age; // global var

    $("input[type='submit']").click(function() {
        var searchName = $("input[name='name']").val(); // take value of text input 

        $.each(json.people.person, function(i, v) {
            if (v.name == searchName) {
                age = v.age; // attach search age to global var
                return;
            }
        });
        return;
    });

Upvotes: 1

imsky
imsky

Reputation: 3289

If your input field is called name you can use the following:

var name = $("input[name='name']").val();
$.each(json.people.person, function(i, v){
if(v.name == name){
...

As for your second requirement, you can just return the v variable instead of returning nothing and alerting the result.

Upvotes: 1

Related Questions