Scratch File Format (2.0)

SandCastleIcon.png This page has links to outside of the Scratch website and Wikipedia. Always remember to stay safe when using the internet since we can't guarantee the safety of other sites.
This article or section documents the current version of Scratch (version 2.0). For this article in Scratch 1.4, see Scratch File Format (1.4).

The Scratch 2.0 file format is the file format used to encode Scratch 2.0 projects when they are downloaded to a user's computer. Unlike the binary Scratch 1.4 file format, the 2.0 format comprises a ZIP archive containing project information encoded in a text-based format called JSON and project media in separate files. Projects conventionally have the extension .sb2, and sprites the extension .sprite2.[1]

Because JSON is a text-based format and many libraries exist for reading and writing JSON files, it is much easier for advanced users to make programs that interact with Scratch files than it was in Scratch 1.4. Users can also easily make modifications to a project by hand in a text editor to achieve things that cannot be done in the Scratch studio; e.g., they can make custom blocks with color inputs or place reporters in slots where they cannot normally be dropped.

JSON

Main article: JSON

JSON, short for JavaScript Object Notation, is the data format used by Scratch 2.0 to store the information and scripts in a project. JSON represents objects with the syntax {"key":value, …}, where key is the string key in double quotation marks and value is the value for that key. Similarly, it represents arrays as [value, …]. Values can be other objects, arrays, strings (delimited by double-quotation marks, e.g., "Arkansas"), numbers (e.g., 100 or 2.718), or Boolean values (true or false).

Syntax

JSON consists of 4 types of objects. The root tag of JSON can either be an object, or an array.

Objects

An object in JSON, is a list of any kind of JSON objects, each object can be referred to individually by its key, which is always a string.

Syntax: "key": object, separated by commas, all inside curly brackets {}

Example: {"User1": ["Hello User2", "Nice day?"], "User2": ["Hi!"], "objIsFor": "chat"}


Arrays

An array in JSON, is a list of any kind of JSON objects, the order of the items is kept. Each item can be referred to with its number (starts at 0) A number is automatically assigned when an object is added to the array, based on how many objects are in the array already.

Syntax: Any type of objects, separated by commas, all inside square brackets []

Example: ["an", "array", "or", "list", {"Type": "object"}]


Strings

A string in JSON is a way of storing text as an object.

Syntax: "value"

Example: "This is a string it is 41 characters long"


Integers

An integer is a number, that cannot contain anything other than numbers

Syntax: 495729471

Example: 1038473924


Floating-Point Numbers

Floating-Point Numbers are just like integers, just they have decimal places.

Syntax: 978329.4383

Example: 24231643.34


Boolean Identifiers

Boolean means True or False. They are represented in JSON by "true" and "false".

Syntax: "true" or "false"

Example: {"has-eye-missing":false, "is-hurt":true}


None

None, represented by "null", means no data. None is usually used to represent nothing, without causing reference errors.

Syntax: "null"

Example: {"second-middle-name":null}


Example

A simple example of JSON syntax:

{"color":"green", "size":3.5, "number_of\"eyes\"":3, "eye_colors":["red","green","blue"], "status":"terminated","alive":true, "children":{"color":"blue", …}}

Since this can be hard to read, this article uses pretty-printed JSON, indenting each sub-element 4 spaces:

{
    "color": "green",
    "size": 3.5,
    "number_of\"eyes\"": 3,
    "eye_colors": [
        "red",
        "green",
        "blue"
    ],
    "status": "terminated",
    "alive": true,
    "children": {
        "color": "blue",
        …
    }
}

Note: Escaping is used in this example

Parsing JSON

Python's json module can be used to read and write JSON data:

import json
json.loads("{}")
json.dumps({"a":[1,2,3]})

JavaScript can also be used, which has a built-in object called JSON that allows you to encode and decode JSON data:

JSON.stringify({a: [1, 2, 3]}) //=> "{\"a\":[1,2,3]}"
JSON.parse("{\"a\":[1,2,3]}") //=> {a: [1, 2, 3]}

json.org provides an extensive list of libraries for parsing and generating JSON in many different programming languages.

Getting Project Data

There is one public way to download get a project.

Downloading a ZIP

You can save a project to your computer from the Scratch studio:

  1. Navigate to the project and click See Inside
  2. Click File > Download to your computer
  3. In the dialog, type a filename and replace the file extension (.sb2) with .zip
  4. Once saved, unarchive it; double-clicking the ZIP will do this on many operating systems

Format

The project metadata, sprites, scripts, and information about project media are all stored in a single JSON file called project.json. The subsections below describe individual objects in that file.

Stage objects

A Stage object is the root object in a project.json file. It contains the following keys and values:

objName
The name of the stage. Usually "Stage", but will change depending on the project's language.
variables
The project's global variables, as an array of Variable objects.
lists
The project's global lists, as an array of List objects.
scripts
The stage's scripts, as an array of script tuples.
scriptComments
The stage's comments, as an array of comment tuples.
sounds
The stage's sounds, as an array of Sound objects.
costumes
The stage's backdrops, as an array of Costume objects.
currentCostumeIndex
The backdrop number of the stage.
penLayerID
The number of the image file in the project ZIP archive containing the pen trails on the stage when the project was saved.
penLayerMD5
The MD5 hash name for the image of the pen trails on the stage when the project was saved.
tempoBPM
The tempo when the project was saved.
videoAlpha
The video transparency when the project was saved.
children
The sprites and stage monitors in the project, as an array of Sprite, StageMonitor, and List objects. Objects which appear later in the array are on top of those which appear earlier.
info
Extra information about the user and the project, as an Info object.

Sprite objects

A Sprite object stores information about a sprite. It contains the following keys and values:

objName
The name of the sprite.
variables
The sprite's variables, as an array of Variable objects.
lists
The sprite's lists, as an array of List objects.
scripts
The sprite's scripts, as an array of script tuples.
scriptComments
The sprite's comments, as an array of comment tuples.
sounds
The sprite's sounds, as an array of Sound objects.
costumes
The sprite's costumes, as an array of Costume objects.
currentCostumeIndex
The costume number of the sprite.
scratchX
The X position of the sprite, relative to the center of the stage.
scratchY
The Y position of the sprite, relative to the center of the stage.
scale
The size of the sprite as a number, where 1 = 100%.
direction
The direction of the sprite as a number in degrees measured clockwise from 0 = upward.
rotationStyle
The rotation style of the sprite as a string; either "normal", "leftRight", or "none"
isDraggable
true if the sprite is draggable; false otherwise.
indexInLibrary
A number indicating the ordering of the sprite in the sprite list.
visible
true if the sprite was shown when the project was saved; false if it was hidden.
spriteInfo
Extra information about the sprite. Currently, this is always an empty object.

StageMonitor objects

A StageMonitor object stores information about a stage monitor. It contains the following keys and values:

target
The name of the stage or sprite to which the stage monitor refers.
Note that the name of the stage matches the objName property of the Stage object, which can vary according to the project's language.
cmd
The type of stage monitor. Valid values are:
cmd Description param
"answer" The answer. null
"backgroundIndex" The backdrop number of the stage. null
"costumeIndex" The costume number of the stage monitor's target. null
"getVar:" A variable monitor. The variable name.
"heading" The direction of the stage monitor's target. null
"scale" The size of the stage monitor's target. null
"sceneName" The backdrop name of the stage. null
"senseVideoMotion" The video motion on the stage monitor's target. "type,thing" where type is motion or direction and thing is Stage or this sprite
"soundLevel" The loudness. null
"tempo" The tempo. null
"timeAndDate" A value of the current () block. "year", "month", "date", "day of week", "hour", "minute", or "second", depending on which one the monitor is showing
"timer" The timer. null
"volume" The volume of the stage monitor's target. null
"xpos" The X position of the stage monitor's target. null
"ypos" The Y position of the stage monitor's target. null
param
A parameter to the stage monitor command. See the table above.
color
The color of the stage monitor, as a hexadecimal color of the form 0xAARRGGBB.
label
The label text for the stage monitor.
mode
The stage monitor mode, either 1, 2, or 3.
mode Meaning
1 Normal readout
2 Large readout
3 Slider (see below for configuration keys)
sliderMin
The minimum value of the stage monitor's slider.
sliderMax
The maximum value of the stage monitor's slider.
isDiscrete
true if the stage monitor's slider should only allow integer values; false otherwise.
x
The X position of the stage monitor, relative to the top-left corner of the stage.
y
The Y position of the stage monitor, relative to the top-left corner of the stage.
visible
true if the stage monitor is shown on the stage; false if it is hidden.

Variable objects

A Variable object stores information about a variable. It contains the following keys and values:

name
The variable name.
value
The variable value.
isPersistent
true if the variable is a cloud variable; false otherwise.

List objects

A List object stores information about a list and its stage monitor. Each list has two corresponding List objects in an SB2 file: one in its sprite's "lists" array (used to show the sprite to which the list belongs) and one in the stage's "children" array (used to show the order of stage monitors and other objects on the stage). It contains the following keys and values:

listName
The list name.
contents
An array of the items in the list.
isPersistent
true if the list is a cloud list; false otherwise.
x
The X position (relative to the top-left corner of the stage) of the stage monitor for the list.
y
The Y position (relative to the top-left corner of the stage) of the stage monitor for the list.
width
The width in pixels of the stage monitor for the list.
height
The height in pixels of the stage monitor for the list.
visible
true if the stage monitor for the list is shown on the stage.

Script tuples

A script tuple stores a script as a JSON array. Each script is an array of length three, in the form [x, y, blocks].

x
The distance between the left edge of the script and the left edge of the scripts area.
y
The distance between the top edge of the script and the top edge of the scripts area.
blocks
The blocks in the script, as an array of block tuples.

For example, this script tuple:

[99,
    50,
    [["whenGreenFlag"],
        ["doUntil", [">", ["timer"], "10"], [["gotoSpriteOrMouse:", "_mouse_"]]],
        ["think:duration:elapsed:from:", "Scratch 2.0 is amazing!", 3]]]

produces this script:

when gf clicked
repeat until <(timer) > [10]>
  go to [mouse-pointer v]
end
think [Scratch 2.0 is amazing!] for (3) secs

and appears 99 pixels to the right and 50 down from the top left of the scripts area when the project is imported into Scratch.

Block tuples

A block tuple stores a block as a JSON array. The first element in the array is an opcode: a string which identifies the block (see Scratch File Format (2.0)/Block Selectors for a list of the opcodes in Scratch 2.0). The remaining elements in the array store the arguments to the block.

Literal values in numeric, textual, or drop-down input slots are stored as numbers or strings. For example:

["wait:elapsed:from:", 1] ["say:", "Hello!"]

Nested reporter blocks are represented as block tuples. For example:

["wait:elapsed:from:", ["*", 3, 2]]

The contents of C blocks are arrays of block tuples. For example:

["doForever", [ ["comeToFront"] ]] ["doIf", ["mousePressed"], [ ["say:", "yes"] ]]

If/else blocks have two arrays. For example:

["doIfElse", ["mousePressed"], [ ["say:", "yes"] ], [ ["say:", "no"] ]]

Custom Blocks

Custom blocks are represented as normal scripts. The procedure definition block follows the format ["procDef", "spec", inputNames, defaultValues, atomic].

spec
A string that identifies the labels and inputs to the block. Plain words produce labels in the block prototype; %c produces an input slot of the type identified by the character c; and %c.menuName produces an input slot of the type identified by the character c with a menu of the type identified by menuName. See here for a full list of input types.
inputNames
An array of input names for each %-slot in spec.
defaultValues
An array of default values for each %-slot in spec.
atomic
true if the block should run without screen refresh; false otherwise.

Comment tuples

A comment tuple stores a comment as a JSON array. Each comment is an array of length seven, in the form [x, y, width, height, isOpen, blockID, text].

x
The distance between the left edge of the comment and the left edge of the scripts area.
y
The distance between the top edge of the comment and the top edge of the scripts area.
width
The width of the comment's frame in pixels.
height
The height of the comment's frame in pixels.
isOpen
true if the comment is a full (expanded) comment; false otherwise.
blockID
The index (in the list of all blocks in the sprite or Stage to which this comment belongs) of the block to which this comment is attached, or -1 if this comment is not attached to a block.
text
The text contents of the comment.

Info objects

An Info object stores information about a project and the studio used to create it. It contains the following keys and values:

scriptCount
The total number of scripts in the project.
videoOn
true if the video was turned on when the project was saved; false otherwise.
spriteCount
The total number of sprites in the project.
swfVersion
The version of the Scratch studio with which the project was saved.
flashVersion
The version of the Flash Player plugin in which the Scratch studio was running.
hasCloudData
true if the project uses cloud data; false otherwise.
userAgent
The user agent string of the browser in which the Scratch studio was running.
projectID
This project's ID on the scratch website.
savedExtensions
The extensions which have been imported into the project, as an array of Extension objects.

An Info object also contains the following keys and values in projects converted from Scratch 1.4 projects:

author
The username of the project's author.
scratch-version
The long version name of Scratch in which the project was created.
os-version
The version of the operating system on which the project was created.
platform
The operating system on which the project was created.
history
A log of all actions performed on the project.
language
The language Scratch was using when the project was saved.
comment
The project notes.

Extension objects

An Extension object stores information about an extension. It contains the following keys and values:

extensionName
The name of the extension.
extensionPort
The port on which the extension runs.
blockSpecs
An array of the extension's block specs.

Media

The media (costumes, sounds, and backgrounds) in the zipped directory are named sequentially from zero with image file extensions for costumes (usually .svg or .png) and audio file extensions for sounds (usually .wav).

Costume objects

A Costume object stores extra metadata for a costume or backdrop. It contains the following keys and values:

costumeName
The name of the costume.
baseLayerID
The number of the corresponding image file in the project ZIP archive.
Note: Value is -1 unless downloaded via Scratch GUI
baseLayerMD5
The MD5 hash of the contents of the costume, followed by a U+002E FULL STOP (.) and the file extension (usually png or svg).
bitmapResolution
In a bitmap costume image, the number of pixels which fit along the X axis of a single screen pixel. Usually 1, or 2 when the costume includes bitmap text.
rotationCenterX
The X coordinate of the costume's rotation center, relative to the top-left of the image.
rotationCenterY
The Y coordinate of the costume's rotation center, relative to the top-left of the image.

A Costume object with text created in the Scratch 1.4 paint editor also contains the following keys and values:

fontName
The name of the font used to display the text.
fontSize
The size of the font used to display the text.
text
The text as a string.
textColor
The color of the text as a hexadecimal color of the form 0xAARRGGBB
textLayerID
The number of the image file containing a rendering of the text in the project ZIP archive.
textLayerMD5
The MD5 hash of the rendering of the text, followed by a U+002E FULL STOP (.) and the file extension (usually png).
textRect
An array of the X and Y positions of the rectangle containing the text, relative to the top-left of the image, followed by the width and height of the rectangle containing the text.

Sound objects

A Sound object stores extra metadata for a sound in either a sprite or the stage. It contains the following keys and values:

soundName
The name of the sound.
soundID
The number of the corresponding sound file in the project ZIP archive.
Note: Value is -1 unless downloaded via Scratch GUI
md5
The MD5 hash of the contents of the sound, followed by a U+002E FULL STOP (.) and the file extension (usually wav).
sampleCount
The number of samples in the sound.
rate
The sampling rate of the sound.
format
A string describing the sound format. Usually the empty string "".

Example Projects

Some example project.json files, exported on Chrome 30.0.1552.0 with Flash player 11.8.800.94 on Mac OS X 10.8.4 with Scratch studio version v341.

An empty project

A blank stage with no sprites or scripts and a single backdrop.

{
    "objName": "Stage",
    "costumes": [{
            "costumeName": "backdrop1",
            "baseLayerID": 1,
            "baseLayerMD5": "510da64cf172d53750dffd23fbf73563.png",
            "bitmapResolution": 1,
            "rotationCenterX": 240,
            "rotationCenterY": 180
        }],
    "currentCostumeIndex": 0,
    "penLayerMD5": "279467d0d49e152706ed66539b577c00.png",
    "tempoBPM": 60,
    "videoAlpha": 0.5,
    "children": [],
    "info": {
        "scriptCount": 0,
        "flashVersion": "MAC 11,8,800,94",
        "spriteCount": 0,
        "swfVersion": "v341",
        "videoOn": false,
        "projectID": "11175527",
        "userAgent": "Mozilla\/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/30.0.1552.0 Safari\/537.36",
        "hasCloudData": false
    }
}

The default project

The project which appears when Create is selected from the header navigation.

{
    "objName": "Stage",
    "sounds": [{
            "soundName": "pop",
            "soundID": 1,
            "md5": "83a9787d4cb6f3b7632b4ddfebf74367.wav",
            "sampleCount": 258,
            "rate": 11025,
            "format": ""
        }],
    "costumes": [{
            "costumeName": "backdrop1",
            "baseLayerID": 3,
            "baseLayerMD5": "510da64cf172d53750dffd23fbf73563.png",
            "bitmapResolution": 1,
            "rotationCenterX": 240,
            "rotationCenterY": 180
        }],
    "currentCostumeIndex": 0,
    "penLayerMD5": "279467d0d49e152706ed66539b577c00.png",
    "tempoBPM": 60,
    "videoAlpha": 0.5,
    "children": [{
            "objName": "Sprite1",
            "sounds": [{
                    "soundName": "meow",
                    "soundID": 0,
                    "md5": "83c36d806dc92327b9e7049a565c6bff.wav",
                    "sampleCount": 18688,
                    "rate": 22050,
                    "format": ""
                }],
            "costumes": [{
                    "costumeName": "costume1",
                    "baseLayerID": 1,
                    "baseLayerMD5": "f9a1c175dbe2e5dee472858dd30d16bb.svg",
                    "bitmapResolution": 1,
                    "rotationCenterX": 47,
                    "rotationCenterY": 55
                },
                {
                    "costumeName": "costume2",
                    "baseLayerID": 2,
                    "baseLayerMD5": "6e8bd9ae68fdb02b7e1e3df656a75635.svg",
                    "bitmapResolution": 1,
                    "rotationCenterX": 47,
                    "rotationCenterY": 55
                }],
            "currentCostumeIndex": 0,
            "scratchX": 0,
            "scratchY": 0,
            "scale": 1,
            "direction": 90,
            "rotationStyle": "normal",
            "isDraggable": false,
            "indexInLibrary": 1,
            "visible": true,
            "spriteInfo": {
            }
        }],
    "info": {
        "scriptCount": 0,
        "flashVersion": "MAC 11,8,800,94",
        "spriteCount": 1,
        "hasCloudData": false,
        "videoOn": false,
        "userAgent": "Mozilla\/5.0 (Macintosh; Intel Mac OS X 10_8_4) AppleWebKit\/537.36 (KHTML, like Gecko) Chrome\/30.0.1552.0 Safari\/537.36",
        "projectID": "11175527",
        "swfVersion": "v341"
    }
}

External Links

References

  1. https://scratcharchive.asun.co/forums/viewtopic.php?id=94297#p1199472

  • This page was last modified on 23 July 2016, at 06:51.