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 const char* JSONReader::kInvalidEscape
=
13 "Invalid escape sequence.";
14 const char* JSONReader::kSyntaxError
=
16 const char* JSONReader::kUnexpectedToken
=
18 const char* JSONReader::kTrailingComma
=
19 "Trailing comma not allowed.";
20 const char* JSONReader::kTooMuchNesting
=
22 const char* JSONReader::kUnexpectedDataAfterRoot
=
23 "Unexpected data after root element.";
24 const char* JSONReader::kUnsupportedEncoding
=
25 "Unsupported encoding. JSON must be UTF-8.";
26 const char* JSONReader::kUnquotedDictionaryKey
=
27 "Dictionary keys must be quoted.";
29 JSONReader::JSONReader()
30 : parser_(new internal::JSONParser(JSON_PARSE_RFC
)) {
33 JSONReader::JSONReader(int options
)
34 : parser_(new internal::JSONParser(options
)) {
37 JSONReader::~JSONReader() {
41 Value
* JSONReader::Read(const StringPiece
& json
) {
42 internal::JSONParser
parser(JSON_PARSE_RFC
);
43 return parser
.Parse(json
);
47 Value
* JSONReader::Read(const StringPiece
& json
,
49 internal::JSONParser
parser(options
);
50 return parser
.Parse(json
);
54 Value
* JSONReader::ReadAndReturnError(const StringPiece
& json
,
57 std::string
* error_msg_out
) {
58 internal::JSONParser
parser(options
);
59 Value
* root
= parser
.Parse(json
);
64 *error_code_out
= parser
.error_code();
66 *error_msg_out
= parser
.GetErrorMessage();
72 std::string
JSONReader::ErrorCodeToString(JsonParseError error_code
) {
76 case JSON_INVALID_ESCAPE
:
77 return kInvalidEscape
;
78 case JSON_SYNTAX_ERROR
:
80 case JSON_UNEXPECTED_TOKEN
:
81 return kUnexpectedToken
;
82 case JSON_TRAILING_COMMA
:
83 return kTrailingComma
;
84 case JSON_TOO_MUCH_NESTING
:
85 return kTooMuchNesting
;
86 case JSON_UNEXPECTED_DATA_AFTER_ROOT
:
87 return kUnexpectedDataAfterRoot
;
88 case JSON_UNSUPPORTED_ENCODING
:
89 return kUnsupportedEncoding
;
90 case JSON_UNQUOTED_DICTIONARY_KEY
:
91 return kUnquotedDictionaryKey
;
98 Value
* JSONReader::ReadToValue(const std::string
& json
) {
99 return parser_
->Parse(json
);
102 JSONReader::JsonParseError
JSONReader::error_code() const {
103 return parser_
->error_code();
106 std::string
JSONReader::GetErrorMessage() const {
107 return parser_
->GetErrorMessage();