2
var data = {
  "obj":[{
    "name": "John",
    "age": "10",
    "Alias": "Person",
    "where":[{"City1":"foo", "City2":"foo2"}]
  },{
    "name": "Mike",
    "age": "",
    "Alias": "Person",
    "where":[{"City1":"test1", "City2":"test2"}]
  }]
}

data.obj[0].Alias and data.obj[1].Alias is duplicate.

Also data.obj[1].age is empty.

if empty or duplicate value exists in JSON object, return false.

How can i check empty and duplicate value?

1

1 Answer 1

1

you can use filter

  1. It will first check for empty age.
  2. If any empty age, it will send false alert. If it sends false alert, that item will not be in the final.
  3. Else it will try to check for duplicate Alias. If any item exists in the temp list that's mean it's already passed once. it will return false.
  4. If no item exists in the temp list, it will push that item in the temp and return true.
  5. if the total item in the final is not same equal to the data that's mean there is a invalid item in the in the json.

Like this

var data = {
  "obj": [{
    "name": "John",
    "age": "10",
    "Alias": "Person",
    "where": [{
      "City1": "foo",
      "City2": "foo2"
    }]
  }, {
    "name": "Mike",
    "age": "",
    "Alias": "Person",
    "where": [{
      "City1": "test1",
      "City2": "test2"
    }]
  }]
}

var temp = []
var final = data.obj.filter((x, y) => {
  console.log(x)
  if (x.age.length == 0) {
    return false
  } else {
    if (temp.indexOf(x.Alias) > -1){
      return false
    }
    else {
       temp.push(x.Alias)
       return true
    }
  }
})

console.log(final.length == data.obj.length ? "Valid" : "Not valid JSON")

DEMO

Sign up to request clarification or add additional context in comments.

1 Comment

i update data.obj[1].age : "11" and data.obj[1].Alias : "Person2". But it still return "not valid Json"...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.