Home  >  Article  >  Web Front-end  >  How does JavaScript determine the authenticity of data in json (code example)

How does JavaScript determine the authenticity of data in json (code example)

不言
不言forward
2019-01-10 10:43:092925browse

The content of this article is about how JavaScript determines the authenticity of data in json (code examples). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

During the project development process, it is often necessary to process json data. During the processing, it is inevitable to judge whether the data is true or false. Here are a few examples summarized for use

json data

const json = {
    a: null,
    b: '',
    c: 'c',
    d: {
        e: 21,
        f: true,
        g: false
    },
    h:1,
    i:0
}
null
let v = json.a
console.log(v)
if (v) {
    console.log('真')
} else {
    console.log('假')
}

Output:
null
False

Empty string
let v = json.b
console.log(v)
if (v) {
    console.log('真')
} else {
    console.log('假')
}

Output:

False

Number 1
let v = json.h
console.log(v)
if (v) {
    console.log('真')
} else {
    console.log('假')
}

Output:
1
True

Number 0
let v = json.i
console.log(v)
if (v) {
    console.log('真')
} else {
    console.log('假')
}

Output:
0
False

Numbers other than numbers 0 and 1
let v = json.d.e
console.log(v)
if (v) {
    console.log('真')
} else {
    console.log('假')
}

Output:
21
True

. Not in the first layer of the object The attribute name
let v = json.j
console.log(v)
if (v) {
    console.log('真')
} else {
    console.log('假')
}

Output:
undefined
false

. The attribute name
let v = json.j.x
console.log(v)
if (v) {
    console.log('真')
} else {
    console.log('假')
}

that is not in the second layer of the object reports an exception, the reason is json.j is undefined If you continue to click, an error will be reported

The above is the detailed content of How does JavaScript determine the authenticity of data in json (code example). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete