Serializing STIX ObjectsΒΆ
The string representation of all STIX classes is a valid STIX JSON object.
In [3]:
from stix2 import Indicator
indicator = Indicator(name="File hash for malware variant",
labels=["malicious-activity"],
pattern="[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']")
print(str(indicator))
Out[3]:
{
"type": "indicator",
"id": "indicator--4336ace8-d985-413a-8e32-f749ba268dc3",
"created": "2018-04-05T20:01:20.012Z",
"modified": "2018-04-05T20:01:20.012Z",
"name": "File hash for malware variant",
"pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']",
"valid_from": "2018-04-05T20:01:20.012209Z",
"labels": [
"malicious-activity"
]
}
However, the 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:
In [4]:
print(indicator.serialize())
Out[4]:
{"name": "File hash for malware variant", "labels": ["malicious-activity"], "pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']", "type": "indicator", "id": "indicator--4336ace8-d985-413a-8e32-f749ba268dc3", "created": "2018-04-05T20:01:20.012Z", "modified": "2018-04-05T20:01:20.012Z", "valid_from": "2018-04-05T20:01:20.012209Z"}
If you need performance but also need human-readable output, you can
pass the indent
keyword argument to serialize()
:
In [5]:
print(indicator.serialize(indent=4))
Out[5]:
{
"name": "File hash for malware variant",
"labels": [
"malicious-activity"
],
"pattern": "[file:hashes.md5 = 'd41d8cd98f00b204e9800998ecf8427e']",
"type": "indicator",
"id": "indicator--4336ace8-d985-413a-8e32-f749ba268dc3",
"created": "2018-04-05T20:01:20.012Z",
"modified": "2018-04-05T20:01:20.012Z",
"valid_from": "2018-04-05T20:01:20.012209Z"
}
The only difference between this and the string representation from
using str()
is that this will not sort the keys. This works because
the keyword arguments are passed to json.dumps()
internally.