1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/json/json_reader.h"
7 #include "base/json/json_parser.h"
8 #include "base/logging.h"
12 // Values 1000 and above are used by JSONFileValueSerializer::JsonFileError.
13 COMPILE_ASSERT(JSONReader::JSON_PARSE_ERROR_COUNT < 1000,
14 json_reader_error_out_of_bounds);
16 const char JSONReader::kInvalidEscape[] =
17 "Invalid escape sequence.";
18 const char JSONReader::kSyntaxError[] =
20 const char JSONReader::kUnexpectedToken[] =
22 const char JSONReader::kTrailingComma[] =
23 "Trailing comma not allowed.";
24 const char JSONReader::kTooMuchNesting[] =
26 const char JSONReader::kUnexpectedDataAfterRoot[] =
27 "Unexpected data after root element.";
28 const char JSONReader::kUnsupportedEncoding[] =
29 "Unsupported encoding. JSON must be UTF-8.";
30 const char JSONReader::kUnquotedDictionaryKey[] =
31 "Dictionary keys must be quoted.";
33 JSONReader::JSONReader()
34 : JSONReader(JSON_PARSE_RFC) {
37 JSONReader::JSONReader(int options)
38 : parser_(new internal::JSONParser(options)) {
41 JSONReader::~JSONReader() {
45 Value* JSONReader::Read(const StringPiece& json) {
46 internal::JSONParser parser(JSON_PARSE_RFC);
47 return parser.Parse(json);
51 Value* JSONReader::Read(const StringPiece& json,
53 internal::JSONParser parser(options);
54 return parser.Parse(json);
58 Value* JSONReader::ReadAndReturnError(const StringPiece& json,
61 std::string* error_msg_out) {
62 internal::JSONParser parser(options);
63 Value* root = parser.Parse(json);
68 *error_code_out = parser.error_code();
70 *error_msg_out = parser.GetErrorMessage();
76 std::string JSONReader::ErrorCodeToString(JsonParseError error_code) {
80 case JSON_INVALID_ESCAPE:
81 return kInvalidEscape;
82 case JSON_SYNTAX_ERROR:
84 case JSON_UNEXPECTED_TOKEN:
85 return kUnexpectedToken;
86 case JSON_TRAILING_COMMA:
87 return kTrailingComma;
88 case JSON_TOO_MUCH_NESTING:
89 return kTooMuchNesting;
90 case JSON_UNEXPECTED_DATA_AFTER_ROOT:
91 return kUnexpectedDataAfterRoot;
92 case JSON_UNSUPPORTED_ENCODING:
93 return kUnsupportedEncoding;
94 case JSON_UNQUOTED_DICTIONARY_KEY:
95 return kUnquotedDictionaryKey;
102 Value* JSONReader::ReadToValue(const std::string& json) {
103 return parser_->Parse(json);
106 JSONReader::JsonParseError JSONReader::error_code() const {
107 return parser_->error_code();
110 std::string JSONReader::GetErrorMessage() const {
111 return parser_->GetErrorMessage();