Update .DEPS.git
[chromium-blink-merge.git] / base / json / json_reader.cc
blob593273ebd44f03f98f8cfdda0fda5ec54a6900da
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"
10 namespace base {
12 const char* JSONReader::kInvalidEscape =
13 "Invalid escape sequence.";
14 const char* JSONReader::kSyntaxError =
15 "Syntax error.";
16 const char* JSONReader::kUnexpectedToken =
17 "Unexpected token.";
18 const char* JSONReader::kTrailingComma =
19 "Trailing comma not allowed.";
20 const char* JSONReader::kTooMuchNesting =
21 "Too much nesting.";
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() {
40 // static
41 Value* JSONReader::Read(const StringPiece& json) {
42 internal::JSONParser parser(JSON_PARSE_RFC);
43 return parser.Parse(json);
46 // static
47 Value* JSONReader::Read(const StringPiece& json,
48 int options) {
49 internal::JSONParser parser(options);
50 return parser.Parse(json);
53 // static
54 Value* JSONReader::ReadAndReturnError(const StringPiece& json,
55 int options,
56 int* error_code_out,
57 std::string* error_msg_out) {
58 internal::JSONParser parser(options);
59 Value* root = parser.Parse(json);
60 if (root)
61 return root;
63 if (error_code_out)
64 *error_code_out = parser.error_code();
65 if (error_msg_out)
66 *error_msg_out = parser.GetErrorMessage();
68 return NULL;
71 // static
72 std::string JSONReader::ErrorCodeToString(JsonParseError error_code) {
73 switch (error_code) {
74 case JSON_NO_ERROR:
75 return std::string();
76 case JSON_INVALID_ESCAPE:
77 return kInvalidEscape;
78 case JSON_SYNTAX_ERROR:
79 return kSyntaxError;
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;
92 default:
93 NOTREACHED();
94 return std::string();
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();
110 } // namespace base