vivjson.viv (2025-03-30)
index
https://github.com/benesult/vivjson-python/tree/main/vivjson/viv.py

API of VivJson
 
Viv.run: Run VivJson's code or deserialize JSON objects.
Viv.parse: Parse VivJson's code and JSON object.
Viv.parse_file: Parse a file that contains VivJson's code or JSON object.
Viv.parse_text: Parse a text that is VivJson's code or JSON object.
Viv.make_instance: Make a class instance.
Viv.make_string: Convert into String. Serialize into JSON string.
 
Environment:
- Python 3.9 or later
 
License:
Copyright 2025 benesult
 
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
 
    http://www.apache.org/licenses/LICENSE-2.0
 
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

 
Modules
       
os

 
Classes
       
builtins.object
Instance
Json
Method
Parsed
Viv

 
class Instance(builtins.object)
    Instance(evaluator: vivjson.evaluator.Evaluator) -> None
 
Instance data class
 
  Methods defined here:
__delattr__(self, name)
__eq__(self, other)
__hash__(self)
__init__(self, evaluator: vivjson.evaluator.Evaluator) -> None
__repr__(self)
__setattr__(self, name, value)

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

Data and other attributes defined here:
__annotations__ = {'evaluator': <class 'vivjson.evaluator.Evaluator'>}
__dataclass_fields__ = {'evaluator': Field(name='evaluator',type=<class 'vivjson.eval...rue,metadata=mappingproxy({}),_field_type=_FIELD)}
__dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=True)

 
class Json(builtins.object)
    Json(value: str) -&gt; None
 
JSON data class
 
  Methods defined here:
__delattr__(self, name)
__eq__(self, other)
__hash__(self)
__init__(self, value: str) -> None
__repr__(self)
__setattr__(self, name, value)

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

Data and other attributes defined here:
__annotations__ = {'value': <class 'str'>}
__dataclass_fields__ = {'value': Field(name='value',type=<class 'str'>,default=<d...rue,metadata=mappingproxy({}),_field_type=_FIELD)}
__dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=True)

 
class Method(builtins.object)
    Method(name: str, arguments: ~METHODARG) -&gt; None
 
Method data class
 
  Methods defined here:
__delattr__(self, name)
__eq__(self, other)
__hash__(self)
__init__(self, name: str, arguments: ~METHODARG) -> None
__repr__(self)
__setattr__(self, name, value)

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

Data and other attributes defined here:
__annotations__ = {'arguments': ~METHODARG, 'name': <class 'str'>}
__dataclass_fields__ = {'arguments': Field(name='arguments',type=~METHODARG,default=<...rue,metadata=mappingproxy({}),_field_type=_FIELD), 'name': Field(name='name',type=<class 'str'>,default=<da...rue,metadata=mappingproxy({}),_field_type=_FIELD)}
__dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=True)

 
class Parsed(builtins.object)
    Parsed(statements: list, instance: Optional[vivjson.viv.Instance]) -&gt; None
 
Parsed data class
 
  Methods defined here:
__delattr__(self, name)
__eq__(self, other)
__hash__(self)
__init__(self, statements: list, instance: Optional[vivjson.viv.Instance]) -> None
__repr__(self)
__setattr__(self, name, value)

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

Data and other attributes defined here:
__annotations__ = {'instance': typing.Optional[vivjson.viv.Instance], 'statements': list[vivjson.statement.Statement]}
__dataclass_fields__ = {'instance': Field(name='instance',type=typing.Optional[vivjs...rue,metadata=mappingproxy({}),_field_type=_FIELD), 'statements': Field(name='statements',type=list[vivjson.statem...rue,metadata=mappingproxy({}),_field_type=_FIELD)}
__dataclass_params__ = _DataclassParams(init=True,repr=True,eq=True,order=False,unsafe_hash=False,frozen=True)

 
class Viv(builtins.object)
    Viv class
 
Attributes:
    EXTENSIONS (tuple[str]): The effective file extensions.
 
  Static methods defined here:
make_instance(*parameters)
Make a class instance.
 
This method runs the given parameters as Constructor.
Then its result will be class instance.
 
For example, a class method is called as below.
 
code = "function test(x, y) {" \
       "  z = x.a + x.b.1 + y" \
       "  return(z)" \
       "}"
map_x = {"a": 100, "b": [1.0, 2.0]}
instance, error_message = Viv.make_instance(code)
result, error_message = \
        Viv.run(instance, Method("test", [map_x, 3]))
print(result)  // 105.0
 
Args:
    parameters (Any): VivJson's codes, JSON values,
                      file paths, variables,
                      Parsed object, or a Configuration
                    str: A VivJson's code, a JSON value, or
                         a file path
                    list[Any] or tuple[Any]: Some VivJson's
                                        codes, JSON values,
                                        some file paths,
                                        variables, or
                                        Parsed objects
                    Json: JSON object
                    dict: Some variables that are name/value
                          pairs.
                    Parsed: The parsed object that is generated
                            with this method. It is passed
                            through toward output.
                    Config: Configuration
 
                    Even if the class instance is contained,
                    it is ignored.
Returns:
    Instance or NoneType, str: Class instance and Error message
                        1st value: Class instance if success,
                                   None otherwise.
                        2nd value: "" if success,
                                   Error message otherwise.
make_string(value, config=None)
Convert a value into string. Serialize a value into JSON string.
 
Configuration is available for Infinity and NaN (Not a Number).
When it is not setting, "" (empty) is returned.
 
Args:
    value (Any): Value
    config (Config or NoneType, optional): Configuration if
                                           needed,
                                           None otherwise.
 
Returns:
    str: Converted value
parse(*parameters)
Parse VivJson's code and JSON object.
 
For example,
parse("a:3,b:2,return(a+b)")
parse(["{a:3,b:2}", "{return(a+b)}"])
parse(["x=", "+", "{a:3,b:2}", "return(x.a+x.b)"])
parse("test.viv")
parse(["test.viv"])
parse("data.json", "calc.viv")
parse(["data.json", "calc.viv"])
parse("{a:3,b:2}", "calc.viv")
parse("x/", Config(enable_stderr=True))  # Error at run-time
parse({"x":[1,2],"y":True},"return(if(y){:=x[0]}else{:=x[1]})")
 
Args:
    parameters (Any): VivJson's codes, JSON values,
                      file paths, variables,
                      Parsed objects, a class instance,
                      a method object, or a Configuration.
                    str: A VivJson's code, a JSON value, or
                         a file path
                    list[Any] or tuple[Any]: Some VivJson's
                                        codes, JSON values,
                                        some file paths,
                                        variables, or
                                        Parsed objects
                    Json: JSON object
                    dict: Some variables that are name/value
                          pairs.
                    Parsed: The parsed object that is generated
                            with this method. It is passed
                            through toward output.
                    Instance: Class instance. It is passed
                              through toward output.
                    Method: Class method information. It is
                            passed through toward output.
                    Config: Configuration
 
Returns:
    Parsed or NoneType, str: Parsed object of script and
                             Error message.
                           1st value: Parsed object if success,
                                      None otherwise
                                      Parsed object has
                                      statements of the given
                                      codes 
                           2nd value: "" if success,
                                      Error message otherwise.
parse_file(file_path: str, config=None)
Parse a file.
 
JSON value and VivJson's code can be parsed.
 
Args:
    file_path (str): The path of file that has JSON value or
                     VivJson's code
    config (Config or NoneType, optional): Configuration if
                                           needed,
                                           None otherwise.
 
Returns:
    Parsed or NoneType, str: Parsed object of script and
                             Error message.
                           1st value: Parsed object if success,
                                      None otherwise.
                                      Parsed object has
                                      statements of the given
                                      codes 
                           2nd value: "" if success,
                                      Error message otherwise.
parse_text(text: str, config=None, argument_index=None)
Parse a text.
 
JSON value and VivJson's code can be parsed.
 
Args:
    text (str): Text that is JSON value or VivJson's code
    config (Config or NoneType, optional): Configuration if
                                           needed,
                                           None otherwise.
    argument_index (int, optional): Argument index (0~)
 
Returns:
    Parsed or NoneType, str: Parsed object of script and
                             Error message.
                           1st value: Parsed object if success,
                                      None otherwise
                                      Parsed object has
                                      statements of the given
                                      codes 
                           2nd value: "" if success,
                                      Error message otherwise.
print_statements(statements, add_class_name=False, config=None)
Print statements.
 
Args:
    statements (list[Statement] or Block): Statements of script
    add_class_name (bool, optional): Class name is added to
                                each statement if this is True.
                                The default is False.
    config (Config or NoneType, optional): Configuration if
                                           needed,
                                           None otherwise.
report_error(error_message: str, enable_stderr=False) -> str
Reports Error.
 
The formatted error is returned.
The formatted error contains Tag looks like [xxxx].
It is outputted into stderr when the argument "enableStderr" is
true. 
 
Args:
    error_message (str): Error message
    enable_stderr (bool, optional): Enablement of stderr. When
                                    it is true, the formatted
                                    error is outputted into
                                    stderr.
                                    The default is False.
 
Returns:
    str: The formatted error
run(*parameters)
Run VivJson's code or deserialize JSON objects.
 
For example,
run("a:3,b:2,return(a+b)")
run(["{a:3,b:2}", "{return(a+b)}"])
run(["x=", "+", "{a:3,b:2}", "return(x.a+x.b)"])
run("test.viv")
run(["test.viv"])
run("data.json", "calc.viv")
run(["data.json", "calc.viv"])
run("{a:3,b:2}", "calc.viv")
run("x/", Config(enable_stderr=True))  # Error at run-time
run({"x":[1,2],"y":True},"return(if(y){:=x[0]}else{:=x[1]})")
 
Args:
    parameters (Any): VivJson's codes, JSON values,
                      file paths, variables,
                      Parsed objects, a class instance,
                      a method object, or a Configuration.
                    str: A VivJson's code, a JSON value, or
                         a file path
                    list[Any] or tuple[Any]: Some VivJson's
                                        codes, JSON values,
                                        some file paths,
                                        variables, or
                                        Parsed objects
                    dict: Some variables that are name/value
                          pairs.
                    Json: JSON object
                    Parsed: The parsed object that is generated
                            with Viv.parse, Viv.parse_text, or
                            Vir.parse_file method.
                    Instance: Class instance. It is passed
                              through toward output.
                    Method: Calling class method.
                            This object has 2 members.
                            "name" is class method name.
                            "arguments" is its arguments.
                    Config: Configuration
 
Returns:
    Any, str: Result and Error message.
              1st value: Result of the given codes if success,
                         None otherwise
              2nd value: "" if success,
                         Error message otherwise.

Data descriptors defined here:
__dict__
dictionary for instance variables (if defined)
__weakref__
list of weak references to the object (if defined)

Data and other attributes defined here:
EXTENSIONS = ('.viv', '.json')

 
Data
        METHODARG = ~METHODARG
Optional = typing.Optional

 
Author
        Fumiaki Motegi <motegi@benesult.com>