简体   繁体   中英

Check json data with javascript if a value exists

I've been trying to parse the following json file (and others like it) to check if the 'Addresses' data contains an [Address][Type] = 'Constituency' (or if [Address][Postcode] has a value - similar problem).

I've tried using the filter function on it, but haven't been able to get anything close to work (and have searched hear for answers and come up blank). I've tried using vanilla javascript and jquery (I'm a beginner at both). Any suggestions?

JSON data sample 1: Has constituency address...

{
  "Members": {
    "script": {
      "-id": "krispX",
      "-type": "text/javascript"
    },
    "Member": {
      "-Member_Id": "199",
      "-Dods_Id": "25747",
      "-Pims_Id": "2358",
      "-Clerks_Id": "77",
      "DisplayAs": "Mr abc def",
      "ListAs": "def, Ms abc",
      "FullTitle": "Mr abc def MP",
      "DateOfBirth": "1968-08-30T00:00:00",
      "DateOfDeath": {
        "-xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
        "-xsi:nil": "true"
      },
      "Gender": "M",
      "Party": {
        "-Id": "15",
        "#text": "My party"
      },
      "House": "Commons",
      "MemberFrom": "Westminster East",
      "HouseStartDate": "1997-05-01T00:00:00",
      "HouseEndDate": {
        "-xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
        "-xsi:nil": "true"
      },
      "CurrentStatus": {
        "-Id": "0",
        "-IsActive": "True",
        "Name": "Current Member",
        "StartDate": "2019-11-11T00:00:00"
      },
      "Addresses": {
        "Address": [
          {
            "-Type_Id": "6",
            "Type": "Website",
            "IsPreferred": "False",
            "IsPhysical": "False",
            "Address1": "http://www.abcdef.org.uk/"
          },
          {
            "-Type_Id": "4",
            "Type": "Constituency",
            "IsPreferred": "False",
            "IsPhysical": "True",
            "Address1": "My party",
            "Address2": "123 qwe rty",
            "Address5": "London",
            "Postcode": "W10 1DZ",
            "Phone": "123 456 7890",
            "Fax": "098 765 4321",
            "Email": "qwerty@asdfgh.uk"
          },
          {
            "-Type_Id": "1",
            "Type": "Parliamentary",
            "IsPreferred": "False",
            "IsPhysical": "True",
            "Address1": "House of Commons",
            "Address5": "London",
            "Postcode": "SW1A 0AA",
            "Phone": "123 456 7890",
            "Fax": "987 654 3210",
            "Email": "qwerty@asdfgh.uk"
          },
          {
            "-Type_Id": "7",
            "Type": "Twitter",
            "IsPreferred": "False",
            "IsPhysical": "False",
            "Address1": "https://twitter.com/qwerty"
          }
        ]
      }
    }
  }
}

...

JSON data sample 2: MISSING constituency address but has postcode...

{
  "Members": {
    "script": {
      "-id": "krispX",
      "-type": "text/javascript"
    },
    "Member": {
      "-Member_Id": "199",
      "-Dods_Id": "25747",
      "-Pims_Id": "2358",
      "-Clerks_Id": "77",
      "DisplayAs": "Mr abc def",
      "ListAs": "def, Ms abc",
      "FullTitle": "Mr abc def MP",
      "DateOfBirth": "1968-08-30T00:00:00",
      "DateOfDeath": {
        "-xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
        "-xsi:nil": "true"
      },
      "Gender": "M",
      "Party": {
        "-Id": "15",
        "#text": "My party"
      },
      "House": "Commons",
      "MemberFrom": "Westminster East",
      "HouseStartDate": "1997-05-01T00:00:00",
      "HouseEndDate": {
        "-xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
        "-xsi:nil": "true"
      },
      "CurrentStatus": {
        "-Id": "0",
        "-IsActive": "True",
        "Name": "Current Member",
        "StartDate": "2019-11-11T00:00:00"
      },
      "Addresses": {
        "Address": [
          {
            "-Type_Id": "6",
            "Type": "Website",
            "IsPreferred": "False",
            "IsPhysical": "False",
            "Address1": "http://www.abcdef.org.uk/"
          },
          {
            "-Type_Id": "1",
            "Type": "Parliamentary",
            "IsPreferred": "False",
            "IsPhysical": "True",
            "Address1": "House of Commons",
            "Address5": "London",
            "Postcode": "SW1A 0AA",
            "Phone": "123 456 7890",
            "Fax": "987 654 3210",
            "Email": "qwerty@asdfgh.uk"
          },
          {
            "-Type_Id": "7",
            "Type": "Twitter",
            "IsPreferred": "False",
            "IsPhysical": "False",
            "Address1": "https://twitter.com/qwerty"
          }
        ]
      }
    }
  }
}

...

Added: JSON data sample 3: Has constituency but has missing postcode (= no postal address)...

{
  "Members": {
    "script": {
      "-id": "krispX",
      "-type": "text/javascript"
    },
    "Member": {
      "-Member_Id": "199",
      "-Dods_Id": "25747",
      "-Pims_Id": "2358",
      "-Clerks_Id": "77",
      "DisplayAs": "Mr abc def",
      "ListAs": "def, Ms abc",
      "FullTitle": "Mr abc def MP",
      "DateOfBirth": "1968-08-30T00:00:00",
      "DateOfDeath": {
        "-xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
        "-xsi:nil": "true"
      },
      "Gender": "M",
      "Party": {
        "-Id": "15",
        "#text": "My party"
      },
      "House": "Commons",
      "MemberFrom": "Westminster East",
      "HouseStartDate": "1997-05-01T00:00:00",
      "HouseEndDate": {
        "-xmlns:xsi": "http://www.w3.org/2001/XMLSchema-instance",
        "-xsi:nil": "true"
      },
      "CurrentStatus": {
        "-Id": "0",
        "-IsActive": "True",
        "Name": "Current Member",
        "StartDate": "2019-11-11T00:00:00"
      },
      "Addresses": {
        "Address": [
          {
            "-Type_Id": "6",
            "Type": "Website",
            "IsPreferred": "False",
            "IsPhysical": "False",
            "Address1": "http://www.abcdef.org.uk/"
          },
          {
            "-Type_Id": "4",
            "Type": "Constituency",
            "IsPreferred": "False",
            "IsPhysical": "True",
            "Phone": "123 456 7890",
            "Email": "qwerty@asdfgh.uk"
          },
          {
            "-Type_Id": "1",
            "Type": "Parliamentary",
            "IsPreferred": "False",
            "IsPhysical": "True",
            "Address1": "House of Commons",
            "Address5": "London",
            "Postcode": "SW1A 0AA",
            "Phone": "123 456 7890",
            "Fax": "987 654 3210",
            "Email": "qwerty@asdfgh.uk"
          },
          {
            "-Type_Id": "7",
            "Type": "Twitter",
            "IsPreferred": "False",
            "IsPhysical": "False",
            "Address1": "https://twitter.com/qwerty"
          }
        ]
      }
    }
  }
}

...

[Edited]

I have found a solution based on Jumshud's answer that works on all three data examples above.

Once I loaded it (of course) with jsondata = JSON.stringify(mydata);// added this because data was coming from php call and it didn't work without it jsondata = JSON.parse(jsondata);

I adapted Jumshud suggestio to be: const hasConstituencyAdrs = jsondata.Members.Member.Addresses.Address.some(address => address.Type === 'Constituency' && address.Postcode && address.Postcode.length > 0);

Which returns true if it has a address key with type=constituency and it also has a postcode key and if the postcode key has a length greater than 0. This returns a true/false which I can now use.

Thanks to everyone for your answers - I've been struggling for 2 days with this and you helped me solve in in under an hour.

You can use the dot-object library with it's get(obj, path, defaultValue) method

This would help to find out if there is any Address with Constituency Type for data sample 1. array some method return value in bool type:

const data1 = JSON.parse(Data sample 1);
const hasConstituencyType = data1.Members.Member.Addresses.Address.some(address => address.Type === 'Constituency')

Output of hasConstituencyType will be true

In order to get Addresses with Postcode values use this:

const adresses = data2.Members.Member.Addresses.Address.filter(address => address.Postcode && address.Postcode.length > 0)

You can parse any json string to a usable JSON var like this:

var json = JSON.parse(jsonString);

If you want to get anything from your json variable, you could do the following:

var type = json.Members.Member.Addresses.Address[0].Type;

I hope this works: You could also read through this: https://www.w3schools.com/js/js_json_objects.asp

As you want to fetch the data from a .json file, in JavaScript you can use fetch API to fetch the data, and apply the logic. Following shows a very naive approach to solution to check Constituency type:


fetch("./data.json")
  .then((result) => {
    return result.json();
  })
  .then((resp) => {
    let jsonData = resp;
    console.log(jsonData);
    const addresses = jsonData.Members.Member.Addresses.Address;
    const check = addresses.filter(element => element.Type === "Constituency");
    if (check) {
      // yes Constituency type is found
    } else {
      // not found
    }
  });

assuming that data.json contains the data you need

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