JSON.parse('true') //trueJSON.parse('false') //falseJSON.parse('str') //Uncaught SyntaxError: Unexpected token d in JSON at position 0JSON.parse('345str') //Uncaught SyntaxError: Unexpected token d in JSON at position 3 ,其报错的位置是出现字符串非数字的时候JSON.parse('345') //345JSON.parse('null') //nullJSON.parse("undefined") //Uncaught SyntaxError: Unexpected token d in JSON at position 0JSON.parse("[]") //[]JSON.parse('[1,"5"]')//[1,"5"]JSON.parse("{}")//{}JSON.parse('{1,5}')//Uncaught SyntaxError: Unexpected token d in JSON at position 1JSON.parse('{1:1}')//Uncaught SyntaxError: Unexpected token d in JSON at position 1JSON.parse('{"name":1}')//{name:1}复制代码
// Parse a JSON array. Position must be right at '['.template Handle
ParseJsonNumber
核心判断了一些负数,0,1-9,小数点等不同情况的处理,并对不符合情况的抛出异常字符。
template Handle JsonParser ::ParseJsonNumber() { bool negative = false; int beg_pos = position_; if (c0_ == '-') { Advance(); negative = true; } if (c0_ == '0') { Advance(); // Prefix zero is only allowed if it's the only digit before // a decimal point or exponent. if (IsDecimalDigit(c0_)) return ReportUnexpectedCharacter(); } else { int i = 0; int digits = 0; if (c0_ < '1' || c0_ > '9') return ReportUnexpectedCharacter(); do { i = i * 10 + c0_ - '0'; digits++; Advance(); } while (IsDecimalDigit(c0_)); if (c0_ != '.' && c0_ != 'e' && c0_ != 'E' && digits < 10) { SkipWhitespace(); return Handle (Smi::FromInt((negative ? -i : i)), isolate()); } } if (c0_ == '.') { Advance(); if (!IsDecimalDigit(c0_)) return ReportUnexpectedCharacter(); do { Advance(); } while (IsDecimalDigit(c0_)); } if (AsciiAlphaToLower(c0_) == 'e') { Advance(); if (c0_ == '-' || c0_ == '+') Advance(); if (!IsDecimalDigit(c0_)) return ReportUnexpectedCharacter(); do { Advance(); } while (IsDecimalDigit(c0_)); } int length = position_ - beg_pos; double number; if (seq_one_byte) { Vector chars(seq_source_->GetChars() + beg_pos, length); number = StringToDouble(isolate()->unicode_cache(), chars, NO_FLAGS, // Hex, octal or trailing junk. std::numeric_limits ::quiet_NaN()); } else { Vector buffer = Vector ::New(length); String::WriteToFlat(*source_, buffer.start(), beg_pos, position_); Vector result = Vector (buffer.start(), length); number = StringToDouble(isolate()->unicode_cache(), result, NO_FLAGS, // Hex, octal or trailing junk. 0.0); buffer.Dispose(); } SkipWhitespace(); return factory()->NewNumber(number, pretenure_);}ParseJsonNumber复制代码
ParseJsonObject
核心判断了末尾是不是}来保证json对象,以及严格校验是否复核键值对的基本格式。
// Parse a JSON object. Position must be right at '{'.template Handle JsonParser ::ParseJsonObject() { HandleScope scope(isolate()); Handle json_object = factory()->NewJSObject(object_constructor(), pretenure_); Handle