Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find value in json [duplicate]

How to fine state name using postcode in bellow json data;

var data = '{
  "1": {
    "state": "VIC",
    "postcode": "2600,2603,2605,2606"
  },
  "2": {
    "state": "NSW",
    "postcode": "2259,2264"
  }
}'

How to find state by postcode;

if i search postcode 2600 if get result like VIC

like image 500
Jayesh Vekariya Avatar asked Dec 24 '15 10:12

Jayesh Vekariya


People also ask

Can JSON have duplicate values?

We can have duplicate keys in a JSON object, and it would still be valid. The validity of duplicate keys in JSON is an exception and not a rule, so this becomes a problem when it comes to actual implementations.

How do you find duplicates in a data set?

If you want to identify duplicates across the entire data set, then select the entire set. Navigate to the Home tab and select the Conditional Formatting button. In the Conditional Formatting menu, select Highlight Cells Rules. In the menu that pops up, select Duplicate Values.

Can JSON have duplicate keys with different values?

http://jsonlint.com/ says yes. http://www.json.org/ doesn't say anything about it being forbidden.


2 Answers

Remove '' as yours is not a valid string, remove '' to make it a valid object literal, then you can iterate over the keys of the Object and check if it has the matching POSTCODE and if it has then return it's corresponding state.

var data = {
  "1": {
    "state": "VIC",
    "postcode": "2600,2603,2605,2606"
  },
  "2": {
    "state": "NSW",
    "postcode": "2259,2264"
  }
};

function getState(data, postcode){

  for(var x in data){
    if(data[x].postcode && data[x].postcode.split(",").indexOf(postcode.toString())!=-1) return data[x].state;
  }
  
  return "Not Found";
  
}

alert(getState(data, "2600"));
alert(getState(data, 2264));

You can directly do .indexOf on the postcode, even without using .split(","). But, then, it will also match with ,2600 which should not be the case. So, use split.

Use json[x].postcode condition to make sure that postcode field exists in the object. Otherwise, it will give an error if it does not exist.

like image 98
void Avatar answered Sep 20 '22 18:09

void


Try like this

var data = '{"1": { "state": "VIC","postcode": "2600,2603,2605,2606"}, "2": {"state": "NSW","postcode": "2259,2264"}}';
var jsObj = JSON.parse(data);
var find = "2600";

var values = Object.keys(jsObj).filter(function(x) {
  return jsObj[x].postcode.indexOf(find) > -1;
}).map(function(x) {
  return jsObj[x].state;
});

console.log(values.length > 0 ? values[0] : "not found");

JSFIDDLE

like image 43
Anik Islam Abhi Avatar answered Sep 19 '22 18:09

Anik Islam Abhi