Serializing STIX Objects

The string representation of all STIX classes is a valid STIX JSON object.

[3]:
from stix2 import Indicator

indicator = Indicator(name="File hash for malware variant",
                      pattern_type="stix",
                      pattern="[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']")

print(indicator.serialize(pretty=True))
[3]:
{
    "type": "indicator",
    "spec_version": "2.1",
    "id": "indicator--5e515461-93ad-41a8-a540-4f9d1a098939",
    "created": "2020-06-26T18:47:20.215931Z",
    "modified": "2020-06-26T18:47:20.215931Z",
    "name": "File hash for malware variant",
    "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']",
    "pattern_type": "stix",
    "pattern_version": "2.1",
    "valid_from": "2020-06-26T18:47:20.215931Z"
}

However, the pretty formatted string representation can be slow, as it sorts properties to be in a more readable order. If you need performance and don’t care about the human-readability of the output, use the object’s serialize() function to pass in any arguments json.dump() would understand:

[4]:
print(indicator.serialize())
[4]:
{"name": "File hash for malware variant", "pattern_type": "stix", "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']", "pattern_version": "2.1", "type": "indicator", "spec_version": "2.1", "id": "indicator--5e515461-93ad-41a8-a540-4f9d1a098939", "created": "2020-06-26T18:47:20.215931Z", "modified": "2020-06-26T18:47:20.215931Z", "valid_from": "2020-06-26T18:47:20.215931Z"}

If you need performance but also need human-readable output, you can pass the indent keyword argument to serialize():

[5]:
print(indicator.serialize(indent=4))
[5]:
{
    "name": "File hash for malware variant",
    "pattern_type": "stix",
    "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']",
    "pattern_version": "2.1",
    "type": "indicator",
    "spec_version": "2.1",
    "id": "indicator--5e515461-93ad-41a8-a540-4f9d1a098939",
    "created": "2020-06-26T18:47:20.215931Z",
    "modified": "2020-06-26T18:47:20.215931Z",
    "valid_from": "2020-06-26T18:47:20.215931Z"
}