Annotation of parser3/src/classes/json.C, revision 1.71

1.1       misha       1: /** @file
                      2:        Parser: @b json parser class.
                      3: 
1.70      moko        4:        Copyright (c) 2000-2026 Art. Lebedev Studio (https://www.artlebedev.com)
1.57      moko        5:        Authors: Konstantin Morshnev <moko@design.ru>
1.1       misha       6: */
                      7: 
                      8: #include "classes.h"
                      9: #include "pa_vmethod_frame.h"
                     10: 
                     11: #include "pa_request.h"
                     12: #include "pa_vbool.h"
1.60      moko       13: #include "pa_varray.h"
1.1       misha      14: 
                     15: #include "pa_charset.h"
                     16: #include "pa_charsets.h"
1.29      moko       17: #include "pa_json.h"
1.1       misha      18: 
1.14      misha      19: #ifdef XML
                     20: #include "pa_vxdoc.h"
                     21: #endif
                     22: 
1.71    ! moko       23: volatile const char * IDENT_JSON_C="$Id: json.C,v 1.70 2026/04/25 13:38:46 moko Exp $";
1.17      moko       24: 
1.1       misha      25: // class
                     26: 
                     27: class MJson: public Methoded {
                     28: public:
                     29:        MJson();
1.64      moko       30: 
                     31:        override Value* get_element(const String&);
                     32:        override const VJunction* put_element(const String&, Value*);
1.1       misha      33: };
                     34: 
                     35: // global variable
                     36: 
1.41      moko       37: DECLARE_CLASS_VAR(json, new MJson);
1.1       misha      38: 
1.64      moko       39: bool handle_array_default=true;
                     40: 
1.1       misha      41: // methods
1.53      moko       42: struct Json : public PA_Allocated {
1.59      moko       43:        Stack<VHashBase*> stack;
1.3       moko       44:        Stack<String*> key_stack;
1.1       misha      45: 
1.3       moko       46:        String* key;
1.1       misha      47:        Value* result;
                     48: 
1.16      misha      49:        Junction* hook_object;
                     50:        Junction* hook_array;
1.3       moko       51:        Request* request;
                     52: 
1.1       misha      53:        Charset *charset;
1.23      moko       54:        String::Language taint;
                     55: 
1.1       misha      56:        bool handle_double;
1.30      misha      57:        bool handle_int;
1.59      moko       58:        bool handle_array;
1.4       moko       59:        enum Distinct { D_EXCEPTION, D_FIRST, D_LAST, D_ALL } distinct;
1.3       moko       60: 
1.23      moko       61:        Json(Charset* acharset): stack(), key_stack(), key(NULL), result(NULL), hook_object(NULL), hook_array(NULL), 
1.30      misha      62:                request(NULL), charset(acharset), taint(String::L_TAINTED), handle_double(true), handle_int(true), 
1.64      moko       63:                handle_array(handle_array_default), distinct(D_EXCEPTION){}
1.4       moko       64: 
                     65:        bool set_distinct(const String &value){
                     66:                if (value == "first") distinct = D_FIRST;
                     67:                else if (value == "last") distinct = D_LAST;
                     68:                else if (value == "all") distinct = D_ALL;
                     69:                else return false;
                     70:                return true;
                     71:        }
1.59      moko       72: 
                     73:        bool set_handle_array(const String &value){
                     74:                if (value == "array") handle_array = true;
                     75:                else if (value == "hash") handle_array = false;
                     76:                else return false;
                     77:                return true;
                     78:        }
1.1       misha      79: };
                     80: 
1.64      moko       81: 
                     82: Value* MJson::get_element(const String& aname) {
                     83:        if (aname=="array"){
                     84:                return new VString(*new String(handle_array_default ? "array" : "hash"));
                     85:        }
                     86:        return Methoded::get_element(aname);
                     87: }
                     88: 
                     89: const VJunction* MJson::put_element(const String& aname, Value* avalue) {
                     90:        if (aname=="array"){
                     91:                Json json(NULL);
                     92:                if (avalue->get_string()){
                     93:                        const String& sarray=avalue->as_string();
                     94:                        if (json.set_handle_array(sarray)){
                     95:                                handle_array_default=json.handle_array;
                     96:                                return 0;
                     97:                        }
                     98:                        throw Exception(PARSER_RUNTIME, &sarray, "$json:array must be 'array' or 'hash'");
                     99:                }
                    100:                throw Exception(PARSER_RUNTIME, 0, "$json:array must be 'array' or 'hash'");
                    101:        }
                    102:        return Methoded::put_element(aname, avalue);
                    103: }
                    104: 
                    105: 
1.1       misha     106: static void set_json_value(Json *json, Value *value){
1.59      moko      107:        VHashBase *top = json->stack.top_value();
1.3       moko      108:        if(json->key == NULL){
1.59      moko      109:                top->add(value);
1.1       misha     110:        } else {
1.4       moko      111:                switch (json->distinct){
                    112:                        case Json::D_EXCEPTION:
                    113:                                if (top->hash().put_dont_replace(*json->key, value))
                    114:                                        throw Exception(PARSER_RUNTIME, json->key, "duplicate key");
                    115:                                break;
                    116:                        case Json::D_FIRST:
                    117:                                top->hash().put_dont_replace(*json->key, value);
                    118:                                break;
                    119:                        case Json::D_LAST:
                    120:                                top->hash().put(*json->key, value);
                    121:                                break;
                    122:                        case Json::D_ALL:
                    123:                                if (top->hash().put_dont_replace(*json->key, value)){
                    124:                                        for(int i=2;;i++){
                    125:                                                String key;
1.62      moko      126:                                                key << *json->key << "_" << pa_uitoa(i);
1.4       moko      127:                                                if (!top->hash().put_dont_replace(key, value)) break;
                    128:                                        }
                    129:                                }
                    130:                                break;
                    131:                }
1.3       moko      132:                json->key=NULL;
1.1       misha     133:        }
                    134: }
                    135: 
1.69      moko      136: String* json_string(Json *json, const char *value){
                    137:        /* do_callback_withbuf guarantees a null-terminated value */
                    138:        if (size_t length = strlen(value)){
                    139:                String::C result = json->charset !=NULL ?
                    140:                        Charset::transcode(String::C(value, length), pa_UTF8_charset, *json->charset) :
                    141:                        String::C(pa_strdup(value, length), length);
                    142:                return new String(result, json->taint);
                    143:        }
                    144:        return (String*)&String::Empty;
1.1       misha     145: }
                    146: 
1.3       moko      147: static Value *json_hook(Request &r, Junction *hook, String* key, Value* value){
1.10      moko      148:        Value *params[]={new VString(key ? *key : String::Empty), value};
1.49      moko      149:        METHOD_FRAME_ACTION(*hook->method, r.method_frame, hook->self, {
                    150:                frame.store_params(params, 2);
                    151:                r.call(frame);
                    152:                return &frame.result();
                    153:        });
1.1       misha     154: }
                    155: 
1.69      moko      156: static int json_callback(Json *json, int type, const char *value, uint32_t)
1.1       misha     157: {
                    158:        switch(type) {
1.25      moko      159:                case JSON_OBJECT_BEGIN:{
1.4       moko      160:                        VHash *v = new VHash();
1.16      misha     161:                        if (json->hook_object){
1.1       misha     162:                                json->key_stack.push(json->key);
1.16      misha     163:                                json->key=NULL;
1.1       misha     164:                        } else {
                    165:                                if (json->stack.count()) set_json_value(json, v);
                    166:                        }
                    167:                        json->stack.push(v);
                    168:                        break;
                    169:                }
1.25      moko      170:                case JSON_OBJECT_END:{
1.16      misha     171:                        if (json->hook_object){
1.3       moko      172:                                String* key = json->key_stack.pop();
1.16      misha     173:                                json->result = json_hook(*json->request, json->hook_object, key, json->stack.pop());
1.1       misha     174:                                
                    175:                                if (json->stack.count()){
                    176:                                        json->key = key;
                    177:                                        set_json_value(json, json->result);
                    178:                                }
                    179:                        } else {
                    180:                                json->result = json->stack.pop();
                    181:                        }
                    182:                        break;
                    183:                }
1.25      moko      184:                case JSON_ARRAY_BEGIN:{
1.16      misha     185:                        if (json->hook_array){
                    186:                                json->key_stack.push(json->key);
                    187:                                json->key=NULL;
1.59      moko      188:                                json->stack.push(new VHash);
1.16      misha     189:                        } else {
1.60      moko      190:                                VHashBase *v = json->handle_array ? (VHashBase *)new VArray : (VHashBase *)new VHash;
1.16      misha     191:                                if (json->stack.count()) set_json_value(json, v);
1.59      moko      192:                                json->stack.push(v);
1.16      misha     193:                        }
1.1       misha     194:                        break;
                    195:                }
1.25      moko      196:                case JSON_ARRAY_END:
1.12      moko      197:                        // libjson supports array at top level, we too
1.16      misha     198:                        if (json->hook_array){
                    199:                                String* key = json->key_stack.pop();
                    200:                                json->result = json_hook(*json->request, json->hook_array, key, json->stack.pop());
                    201:                                
                    202:                                if (json->stack.count()){
                    203:                                        json->key = key;
                    204:                                        set_json_value(json, json->result);
                    205:                                }
                    206:                        } else {
                    207:                                json->result = json->stack.pop();
                    208:                        }
1.1       misha     209:                        break;
1.25      moko      210:                case JSON_KEY:
1.69      moko      211:                        json->key = json_string(json, value);
1.16      misha     212:                        break;
1.25      moko      213:                case JSON_INT:
1.30      misha     214:                        if (json->handle_int){
1.69      moko      215:                                set_json_value(json, new VDouble( json_string(json, value)->as_double() ));
1.30      misha     216:                        } else {
                    217:                                // JSON_STRING
1.69      moko      218:                                set_json_value(json, new VString(*json_string(json, value)));
1.30      misha     219:                        }
1.1       misha     220:                        break;
1.25      moko      221:                case JSON_FLOAT:
1.1       misha     222:                        if (json->handle_double){
1.69      moko      223:                                set_json_value(json, new VDouble( json_string(json, value)->as_double() ));
1.1       misha     224:                                break;
1.25      moko      225:                        } // else is JSON_STRING
                    226:                case JSON_STRING:
1.69      moko      227:                        set_json_value(json, new VString(*json_string(json, value)));
1.1       misha     228:                        break;
1.25      moko      229:                case JSON_NULL:
1.18      moko      230:                        set_json_value(json, VVoid::get());
1.1       misha     231:                        break;
1.25      moko      232:                case JSON_TRUE:
1.1       misha     233:                        set_json_value(json, &VBool::get(true));
                    234:                        break;
1.25      moko      235:                case JSON_FALSE:
1.1       misha     236:                        set_json_value(json, &VBool::get(false));
1.25      moko      237:                        break;
1.1       misha     238:        }
1.25      moko      239:        return 0;
1.1       misha     240: }
                    241: 
1.5       moko      242: static const char* json_error_message(int error_code){
                    243:        static const char* error_messages[] = {
1.1       misha     244:                NULL,
1.25      moko      245:                "out of memory",
                    246:                "bad character",
                    247:                "stack empty",
                    248:                "pop unexpected mode",
                    249:                "nesting limit",
                    250:                "data limit",
                    251:                "comment not allowed by config",
1.35      moko      252:                "unexpected character",
1.25      moko      253:                "missing unicode low surrogate",
                    254:                "unexpected unicode low surrogate",
                    255:                "error comma out of structure",
                    256:                "error in a callback"
1.1       misha     257:        };
                    258:        return error_messages[error_code];
                    259: }
                    260: 
1.35      moko      261: #define SOURCE_MAX_LEN 60
                    262: 
                    263: void json_exception_with_source(Request& r, const char* msg, const char* json, int offset){
                    264:        int i;
                    265: 
                    266:        int line=0;
                    267:        int start=0;
                    268:        int end=strlen(json);
                    269: 
                    270:        if(offset>end)
                    271:                offset=end;
                    272: 
                    273:        for(i = 0; i < offset; i++){
                    274:                if(json[i]=='\n'){
                    275:                        line++;
                    276:                }
                    277:        }
                    278: 
                    279:        if(offset > SOURCE_MAX_LEN/2)
                    280:                start = offset - SOURCE_MAX_LEN/2;
                    281: 
                    282:        for(i = offset-1; i>=start; i--){
                    283:                if(json[i]=='\n'){
                    284:                        start=i+1;
                    285:                        break;
                    286:                }
                    287:        }
                    288: 
                    289:        if(start+SOURCE_MAX_LEN < end)
                    290:                end=start+SOURCE_MAX_LEN;
                    291: 
                    292:        for(i = offset+1; i<end; i++){
                    293:                if(json[i]=='\n'){
                    294:                        end=i;
                    295:                        break;
                    296:                }
                    297:        }
                    298: 
                    299:        char *source = pa_strdup(json+start, end-start);
                    300:        int source_offset = offset-start;
                    301: 
                    302:        if(source[source_offset]=='\n')
                    303:                source[source_offset]=' ';
                    304: 
                    305:        for(i = 0; i < source_offset; i++){
                    306:                if(source[i]=='\t'){
                    307:                        source[i]=' ';
                    308:                }
                    309:        }
                    310: 
                    311:        if(r.charsets.source().isUTF8()){
                    312:                source=(char *)fixUTF8(source);
                    313:                if(source_offset>0){
                    314:                        String s_source(pa_strdup(source,source_offset));
                    315:                        source_offset=s_source.length(r.charsets.source());
                    316:                }
                    317:        }
                    318: 
                    319:        throw Exception("json.parse", 0, "%s at line %d\n%s\n%*s", msg, line+1, source, source_offset+1, "^");
                    320: }
                    321: 
1.1       misha     322: static void _parse(Request& r, MethodParams& params) {
1.3       moko      323:        const String& json_string=params.as_string(0, "json must be string");
                    324: 
                    325:        Json json(r.charsets.source().isUTF8() ? NULL : &(r.charsets.source()));
1.1       misha     326: 
1.25      moko      327:        json_config config = {
                    328:                0,              // buffer_initial_size
1.26      moko      329:                128,            // max_nesting
1.25      moko      330:                0,              // max_data
                    331:                1,              // allow_c_comments
                    332:                1,              // allow_yaml_comments
                    333:                pa_malloc,
                    334:                pa_realloc,
                    335:                pa_free
                    336:        };
1.1       misha     337: 
                    338:        if(params.count() == 2)
                    339:                if(HashStringValue* options=params.as_hash(1)) {
                    340:                        int valid_options=0;
                    341:                        if(Value* value=options->get("depth")) {
1.46      moko      342:                                config.max_nesting=r.process(*value).as_int();
1.1       misha     343:                                valid_options++;
                    344:                        }
                    345:                        if(Value* value=options->get("double")) {
1.46      moko      346:                                json.handle_double=r.process(*value).as_bool();
1.4       moko      347:                                valid_options++;
                    348:                        }
1.30      misha     349:                        if(Value* value=options->get("int")) {
1.46      moko      350:                                json.handle_int=r.process(*value).as_bool();
1.30      misha     351:                                valid_options++;
                    352:                        }
1.4       moko      353:                        if(Value* value=options->get("distinct")) {
                    354:                                const String& sdistinct=value->as_string();
                    355:                                if (!json.set_distinct(sdistinct))
                    356:                                        throw Exception(PARSER_RUNTIME, &sdistinct, "must be 'first', 'last' or 'all'");
1.1       misha     357:                                valid_options++;
                    358:                        }
1.23      moko      359:                        if(Value* value=options->get("taint")) {
1.71    ! moko      360:                                json.taint=String::name2lang(value->as_string());
1.23      moko      361:                                valid_options++;
                    362:                        }
1.1       misha     363:                        if(Value* value=options->get("object")) {
1.16      misha     364:                                json.hook_object=value->get_junction();
1.3       moko      365:                                json.request=&r;
1.49      moko      366:                                if (!json.hook_object || !json.hook_object->method || !json.hook_object->method->params_names || !(json.hook_object->method->params_count == 2))
1.1       misha     367:                                        throw Exception(PARSER_RUNTIME, 0, "$.object must be parser method with 2 parameters");
                    368:                                valid_options++;
                    369:                        }
1.16      misha     370:                        if(Value* value=options->get("array")) {
1.59      moko      371:                                if(value->get_string()){
                    372:                                        const String& sarray=value->as_string();
                    373:                                        if (!json.set_handle_array(sarray))
                    374:                                                throw Exception(PARSER_RUNTIME, &sarray, "$.array must be parser method with 2 parameters or 'array' or 'hash'");
                    375:                                } else {
                    376:                                        json.hook_array=value->get_junction();
                    377:                                        json.request=&r;
                    378:                                        if (!json.hook_array || !json.hook_array->method || !json.hook_array->method->params_names || !(json.hook_array->method->params_count == 2))
                    379:                                                throw Exception(PARSER_RUNTIME, 0, "$.array must be parser method with 2 parameters or 'array' or 'hash'");
                    380:                                }
1.16      misha     381:                                valid_options++;
                    382:                        }
1.1       misha     383:                        if(valid_options!=options->count())
                    384:                                throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
                    385:                }
                    386: 
1.28      moko      387:        const String::Body json_body = json_string.cstr_to_string_body_untaint(String::L_JSON, r.connection(false), &r.charsets);
1.44      moko      388:        const char *json_cstr = json.charset != NULL ? Charset::transcode(json_body, *json.charset, pa_UTF8_charset).cstr() : json_body.cstr();
1.1       misha     389: 
1.25      moko      390:        json_parser parser;
                    391:        if(int result = json_parser_init(&parser, &config, (json_parser_callback)&json_callback, &json))
                    392:                throw Exception("json.parse", 0, "%s", json_error_message(result));
                    393: 
1.36      moko      394:        if(!*json_cstr)
                    395:                throw Exception("json.parse", 0, "empty string is not valid json");
                    396: 
                    397:        const char *first_quote=strchr(json_cstr,'"');
                    398:        if(first_quote && first_quote>json_cstr && *(--first_quote) == '\\')
                    399:                json_exception_with_source(r, "illegal quote escape, json may be tainted", json_cstr, first_quote-json_cstr);
                    400: 
1.25      moko      401:        uint32_t processed;
                    402:        if(int result = json_parser_string(&parser, json_cstr, strlen(json_cstr), &processed))
1.35      moko      403:                json_exception_with_source(r, json_error_message(result), json_cstr, processed);
1.3       moko      404: 
1.25      moko      405:        if (!json_parser_is_done(&parser))
1.35      moko      406:                json_exception_with_source(r, "unexpected end of json data", json_cstr, processed);
                    407: 
1.25      moko      408:        json_parser_free(&parser);
1.1       misha     409: 
1.48      moko      410:        if (json.result) r.write(*json.result);
1.1       misha     411: }
                    412: 
1.63      moko      413: const uint ANTI_ENDLESS_JSON_STRING_RECURSION=128;
1.26      moko      414: 
1.8       moko      415: char *get_indent(uint level){
1.63      moko      416:        static char* cache[ANTI_ENDLESS_JSON_STRING_RECURSION]={};
1.8       moko      417:        if (!cache[level]){
1.56      moko      418:                char *result = static_cast<char*>(pa_malloc_atomic(level+1));
1.8       moko      419:                memset(result, '\t', level);
1.9       moko      420:                result[level]='\0';
1.8       moko      421:                return cache[level]=result;
                    422:        }
                    423:        return cache[level];
                    424: }
                    425: 
1.56      moko      426: String *get_delim(uint level){
1.63      moko      427:        static String* cache[ANTI_ENDLESS_JSON_STRING_RECURSION]={};
1.56      moko      428: 
                    429:        if (!cache[level]){
                    430:                char *result = static_cast<char*>(pa_malloc_atomic(level+2+1+1));
                    431:                result[0]=',';
                    432:                result[1]='\n';
                    433:                memset(result+2, '\t', level);
                    434:                result[level+2]='"';
                    435:                result[level+3]='\0';
                    436:                return cache[level] = new String(result, String::L_AS_IS);
                    437:        }
                    438:        return cache[level];
                    439: }
                    440: 
1.59      moko      441: String *get_array_delim(uint level){
1.63      moko      442:        static String* cache[ANTI_ENDLESS_JSON_STRING_RECURSION]={};
1.59      moko      443: 
                    444:        if (!cache[level]){
                    445:                char *result = static_cast<char*>(pa_malloc_atomic(level+2+1));
                    446:                result[0]=',';
                    447:                result[1]='\n';
                    448:                memset(result+2, '\t', level);
                    449:                result[level+2]='\0';
                    450:                return cache[level] = new String(result, String::L_AS_IS);
                    451:        }
                    452:        return cache[level];
                    453: }
                    454: 
1.63      moko      455: class Json_string_recursion {
1.26      moko      456:        Json_options& foptions;
                    457: public:
1.63      moko      458:        Json_string_recursion(Json_options& aoptions) : foptions(aoptions) {
                    459:                if(++foptions.json_string_recursion==ANTI_ENDLESS_JSON_STRING_RECURSION)
1.26      moko      460:                        throw Exception(PARSER_RUNTIME, 0, "call canceled - endless json recursion detected");
                    461:        }
1.63      moko      462:        ~Json_string_recursion() {
                    463:                if(foptions.json_string_recursion)
                    464:                        foptions.json_string_recursion--;
1.26      moko      465:        }
                    466: };
                    467: 
1.21      moko      468: const String& value_json_string(String::Body key, Value& v, Json_options& options);
1.6       misha     469: 
1.37      moko      470: const String* Json_options::hash_json_string(HashStringValue *hash) {
                    471:        if(!hash || !hash->count())
1.21      moko      472:                return new String("{}", String::L_AS_IS);
1.8       moko      473: 
1.63      moko      474:        Json_string_recursion go_down(*this);
1.8       moko      475: 
                    476:        String& result = *new String("{\n", String::L_AS_IS);
                    477: 
1.21      moko      478:        if (indent){
1.8       moko      479: 
                    480:                String *delim=NULL;
1.63      moko      481:                indent=get_indent(json_string_recursion);
1.37      moko      482:                for(HashStringValue::Iterator i(*hash); i; i.next() ){
1.8       moko      483:                        if (delim){
                    484:                                result << *delim;
                    485:                        } else {
1.21      moko      486:                                result << indent << "\"";
1.63      moko      487:                                delim = get_delim(json_string_recursion);
1.8       moko      488:                        }
1.21      moko      489:                        result << String(i.key(), String::L_JSON) << "\":" << value_json_string(i.key(), *i.value(), *this);
1.8       moko      490:                }
1.63      moko      491:                result << "\n" << (indent=get_indent(json_string_recursion-1)) << "}";
1.6       misha     492: 
1.8       moko      493:        } else {
                    494: 
                    495:                bool need_delim=false;
1.37      moko      496:                for(HashStringValue::Iterator i(*hash); i; i.next() ){
1.8       moko      497:                        result << (need_delim ? ",\n\"" : "\"");
1.21      moko      498:                        result << String(i.key(), String::L_JSON) << "\":" << value_json_string(i.key(), *i.value(), *this);
1.8       moko      499:                        need_delim=true;
                    500:                }
                    501:                result << "\n}";
1.6       misha     502: 
                    503:        }
                    504: 
1.21      moko      505:        return &result;
1.6       misha     506: }
                    507: 
1.59      moko      508: const String* Json_options::array_json_string(ArrayValue *array) {
                    509:        if(!array || !array->count())
                    510:                return new String("[]", String::L_AS_IS);
                    511: 
1.63      moko      512:        Json_string_recursion go_down(*this);
1.59      moko      513: 
                    514:        String& result = *new String("[\n", String::L_AS_IS);
                    515: 
                    516:        if (indent){
                    517: 
                    518:                String *delim=NULL;
1.63      moko      519:                indent=get_indent(json_string_recursion);
1.59      moko      520:                for(ArrayValue::Iterator i(*array); i; i.next() ){
                    521:                        if (delim){
                    522:                                result << *delim;
                    523:                        } else {
                    524:                                result << indent;
1.63      moko      525:                                delim = get_array_delim(json_string_recursion);
1.59      moko      526:                        }
1.67      moko      527:                        result << value_json_string(String::Body::uitoa(i.index()), i.value() ? *i.value() : static_cast<Value&>(*VVoid::get()), *this);
1.59      moko      528:                }
1.63      moko      529:                result << "\n" << (indent=get_indent(json_string_recursion-1)) << "]";
1.59      moko      530: 
                    531:        } else {
                    532: 
                    533:                bool need_delim=false;
                    534:                for(ArrayValue::Iterator i(*array); i; i.next() ){
                    535:                        if(need_delim) result << ",\n";
1.67      moko      536:                        result << value_json_string(String::Body::uitoa(i.index()), i.value() ? *i.value() : static_cast<Value&>(*VVoid::get()), *this);
1.59      moko      537:                        need_delim=true;
                    538:                }
                    539:                result << "\n]";
                    540: 
                    541:        }
                    542: 
                    543:        return &result;
                    544: }
                    545: 
                    546: const String* Json_options::array_compact_json_string(ArrayValue *array) {
                    547:        if(!array || !array->count())
                    548:                return new String("[]", String::L_AS_IS);
                    549: 
1.63      moko      550:        Json_string_recursion go_down(*this);
1.59      moko      551: 
                    552:        String& result = *new String("[\n", String::L_AS_IS);
                    553: 
                    554:        if (indent){
                    555: 
                    556:                String *delim=NULL;
1.63      moko      557:                indent=get_indent(json_string_recursion);
1.59      moko      558:                for(ArrayValue::Iterator i(*array); i; i.next() ){
                    559:                        if (i.value()){
                    560:                                if (delim){
                    561:                                        result << *delim;
                    562:                                } else {
                    563:                                        result << indent;
1.63      moko      564:                                        delim = get_array_delim(json_string_recursion);
1.59      moko      565:                                }
1.67      moko      566:                                result << value_json_string(String::Body::uitoa(i.index()), *i.value(), *this);
1.59      moko      567:                        }
                    568:                }
1.63      moko      569:                result << "\n" << (indent=get_indent(json_string_recursion-1)) << "]";
1.59      moko      570: 
                    571:        } else {
                    572: 
                    573:                bool need_delim=false;
                    574:                for(ArrayValue::Iterator i(*array); i; i.next() ){
                    575:                        if (i.value()){
                    576:                                if(need_delim) result << ",\n";
1.67      moko      577:                                result << value_json_string(String::Body::uitoa(i.index()), *i.value(), *this);
1.59      moko      578:                                need_delim=true;
                    579:                        }
                    580:                }
                    581:                result << "\n]";
                    582: 
                    583:        }
                    584: 
                    585:        return &result;
                    586: }
                    587: 
1.21      moko      588: static bool based_on(HashStringValue::key_type key, HashStringValue::value_type /*value*/, Value* v) {
1.15      misha     589:        return v->is(key.cstr());
                    590: }
1.26      moko      591: 
1.21      moko      592: const String& value_json_string(String::Body key, Value& v, Json_options& options) {
                    593:        if(options.methods) {
                    594:                Value* method=options.methods->get(v.type());
                    595:                if(!method){
                    596:                        method=options.methods->first_that<Value*>(based_on, &v);
1.31      misha     597:                        options.methods->put(v.type(), method ? method : VVoid::get());
1.21      moko      598:                }
                    599:                if(method && !method->is_void()) {
1.67      moko      600:                        static const String::Body sindent("indent");
1.6       misha     601:                        Junction* junction=method->get_junction();
1.26      moko      602:                        HashStringValue* params_hash=options.params && options.indent ? options.params->get_hash() : NULL;
1.67      moko      603:                        Temp_hash_value<HashStringValue, Value*> indent(params_hash, sindent, new VString(*new String(options.indent, String::L_AS_IS)));
1.26      moko      604: 
1.21      moko      605:                        Value *params[]={new VString(*new String(key, String::L_JSON)), &v, options.params ? options.params : VVoid::get()};
1.6       misha     606: 
1.49      moko      607:                        METHOD_FRAME_ACTION(*junction->method, options.r->method_frame, junction->self, {
                    608:                                frame.store_params(params, 3);
                    609:                                options.r->call(frame);
                    610:                                return frame.result().as_string();
                    611:                        });
1.6       misha     612:                }
1.15      misha     613:        }
1.6       misha     614: 
1.21      moko      615:        options.key=key;
1.6       misha     616:        return *v.get_json_string(options);
                    617: }
                    618: 
                    619: static void _string(Request& r, MethodParams& params) {
                    620:        Json_options json(&r);
                    621: 
                    622:        if(params.count() == 2)
                    623:                if(HashStringValue* options=params.as_hash(1)) {
1.47      moko      624:                        json.params=&params[1];
1.6       misha     625:                        HashStringValue* methods=new HashStringValue();
1.14      misha     626:                        HashStringValue* vvalue;
1.6       misha     627:                        for(HashStringValue::Iterator i(*options); i; i.next() ){
                    628:                                String::Body key=i.key();
                    629:                                Value* value=i.value();
                    630:                                if(key == "skip-unknown"){
1.46      moko      631:                                        json.skip_unknown=r.process(*value).as_bool();
1.50      moko      632:                                } else if(key == "one-line"){
                    633:                                        json.one_line=r.process(*value).as_bool();
1.6       misha     634:                                } else if(key == "date" && value->is_string()){
                    635:                                        const String& svalue=value->as_string();
                    636:                                        if(!json.set_date_format(svalue))
1.38      moko      637:                                                throw Exception(PARSER_RUNTIME, &svalue, "must be 'sql-string', 'gmt-string', 'iso-string' or 'unix-timestamp'");
1.8       moko      638:                                } else if(key == "indent"){
1.26      moko      639:                                        if(value->is_string()){
                    640:                                                json.indent=value->as_string().cstr();
1.63      moko      641:                                                json.json_string_recursion=strlen(json.indent);
1.46      moko      642:                                        } else json.indent=r.process(*value).as_bool() ? "" : NULL;
1.6       misha     643:                                } else if(key == "table" && value->is_string()){
                    644:                                        const String& svalue=value->as_string();
                    645:                                        if(!json.set_table_format(svalue))
1.13      moko      646:                                                throw Exception(PARSER_RUNTIME, &svalue, "must be 'array', 'object' or 'compact'");
1.59      moko      647:                                } else if(key == "array" && value->is_string()){
                    648:                                        const String& svalue=value->as_string();
                    649:                                        if(!json.set_array_format(svalue))
                    650:                                                throw Exception(PARSER_RUNTIME, &svalue, "must be 'array', 'object' or 'compact'");
1.6       misha     651:                                } else if(key == "file" && value->is_string()){
                    652:                                        const String& svalue=value->as_string();
                    653:                                        if(!json.set_file_format(svalue))
1.19      misha     654:                                                throw Exception(PARSER_RUNTIME, &svalue, "must be 'base64', 'text' or 'stat'");
1.32      misha     655:                                } else if(key == "void" && value->is_string()){
                    656:                                        const String& svalue=value->as_string();
                    657:                                        if(!json.set_void_format(svalue))
                    658:                                                throw Exception(PARSER_RUNTIME, &svalue, "must be 'string' or 'null'");
1.14      misha     659: #ifdef XML
                    660:                                } else if(key == "xdoc" && (vvalue = value->get_hash())){
1.24      moko      661:                                        json.xdoc_options=new XDocOutputOptions();
                    662:                                        json.xdoc_options->append(r, vvalue);
1.14      misha     663: #endif
1.6       misha     664:                                } else if(Junction* junction=value->get_junction()){
1.49      moko      665:                                        if(!junction->method || !junction->method->params_names || junction->method->params_count != 3)
1.13      moko      666:                                                throw Exception(PARSER_RUNTIME, 0, "$.%s must be parser method with 3 parameters", key.cstr());
1.6       misha     667:                                        methods->put(key, value);
1.68      moko      668:                                } else
                    669:                                        throw Exception(PARSER_RUNTIME, 0, CALLED_WITH_INVALID_OPTION);
1.6       misha     670:                        }
1.22      moko      671: 
                    672:                        // special handling for $._default 
1.61      moko      673:                        if(VHashBase* vhash=dynamic_cast<VHashBase*>(&params[1]))
1.22      moko      674:                                if(Value* value=vhash->get_default()) {
1.34      misha     675:                                        if(!value->is_string()){
1.43      moko      676:                                                Junction* junction=value->get_junction();
1.49      moko      677:                                                if(!junction || !junction->method || !junction->method->params_names || junction->method->params_count != 3)
1.42      moko      678:                                                        throw Exception(PARSER_RUNTIME, 0, "$._default must be string or parser method with 3 parameters");
1.34      misha     679:                                        }
1.22      moko      680:                                        json.default_method=value;
                    681:                                }
                    682: 
1.6       misha     683:                        if(methods->count())
                    684:                                json.methods=methods;
                    685:                }
1.14      misha     686: 
1.46      moko      687:        const String& result_string=value_json_string(String::Body(), r.process(params[0]), json);
1.28      moko      688:        String::Body result_body=result_string.cstr_to_string_body_untaint(String::L_JSON, r.connection(false), &r.charsets);
1.50      moko      689:        if(json.one_line){
                    690:                char *result=result_body.cstrm();
                    691:                for(char *c=result;*c;c++)
                    692:                        if(*c=='\n')
                    693:                                *c=' ';
1.67      moko      694:                result_body=String::Body(result);
1.50      moko      695:        }
1.48      moko      696:        r.write(*new String(result_body, String::L_AS_IS));
1.50      moko      697: }
1.6       misha     698: 
1.1       misha     699: // constructor
                    700: 
                    701: MJson::MJson(): Methoded("json") {
                    702:        add_native_method("parse", Method::CT_STATIC, _parse, 1, 2);
1.6       misha     703: 
1.58      moko      704:        add_native_method("string", Method::CT_STATIC, _string, 1, 2);
1.1       misha     705: }

E-mail: