Warning, /education/gcompris/src/core/JsonParser.qml is written in an unsupported language. File is not indexed.
0001 /* GCompris - JsonParser.qml 0002 * 0003 * SPDX-FileCopyrightText: 2014 Holger Kaelberer <holger.k@elberer.de> 0004 * 0005 * Authors: 0006 * Holger Kaelberer <holger.k@elberer.de> 0007 * 0008 * SPDX-License-Identifier: GPL-3.0-or-later 0009 */ 0010 0011 import QtQuick 2.12 0012 import GCompris 1.0 0013 0014 /** 0015 * A QML helper component for loading and validating JSON data. 0016 * @ingroup components 0017 * 0018 * @inherit QtQuick.Item 0019 */ 0020 QtObject { 0021 id: jsonparser 0022 0023 /** 0024 * type:File 0025 * File with json content to parse. 0026 */ 0027 property File jsonFile: File { 0028 id: jsonfile 0029 name: "" 0030 0031 onError: jsonparser.error(msg); 0032 } 0033 0034 /** 0035 * Emitted upon error. 0036 * 0037 * @param msg Error message. 0038 */ 0039 signal error(string msg); 0040 0041 /* public interface: */ 0042 0043 /** 0044 * Parse the passed json string and return a corresponding object. 0045 * 0046 * @param type:string json JSON string to parse. 0047 * @param type:function validateFunc Function used to semantically validate 0048 * the parsed json [optional]. 0049 * The function must have the signature 0050 * <tt>bool validateFunc(jsonString)</tt> 0051 * and return @c true if json string is semantically 0052 * valid, @c false otherwise. 0053 * @returns The object parsed from json if valid, @c null if json is 0054 * syntactically or semantically invalid. 0055 */ 0056 function parseString(json, validateFunc) 0057 { 0058 var doc; 0059 try { 0060 doc = JSON.parse(json); 0061 // validate if requested: 0062 if (validateFunc !== undefined 0063 && !validateFunc(doc)) { 0064 error("JsonParser: JSON is semantically invalid"); 0065 return null; 0066 } 0067 } catch(e) { 0068 error("JsonParser: JSON is syntactically invalid: " + e); 0069 return null; 0070 } 0071 return doc; 0072 } 0073 0074 /** 0075 * Parse a json string from the given url and return a corresponding 0076 * object. 0077 * 0078 * @param type:string url Source URL for the json file to parse. 0079 * Supported URL-schemes: file://, qrc://. 0080 * @param type:functions validateFunc cf. @ref parseString 0081 * @returns cf. @ref parseString 0082 */ 0083 function parseFromUrl(url, validateFunc) 0084 { 0085 var json = "'"; 0086 if (url.substring(0,3) === "qrc" || url.substring(0,4) === "file" 0087 || url.substring(0,1) === ":") { 0088 json = jsonFile.read(url); 0089 if (json !== "") 0090 return parseString(json, validateFunc); 0091 } else if (url.substring(0,4) === "http") 0092 error("http:// scheme not yet implemented"); 0093 else // unknown url scheme 0094 error("Unknown url scheme in url parameter: " + url); 0095 return null; 0096 } 0097 }