This topic describes the function you can use to manipulate JSON data.
Function | Description and Example |
---|---|
JSON.parse(str) |
Converts a string to a JSON object. JSON.parse('{"a":1}'); The above example returns the JSON object {"a":1}. If this object is sent to an output property of the Script dataflow block, the object is converted to a string, and the block property holds a string. |
JSON.stringify(obj) |
Converts a JSON object to a string. The following example returns the string {"a":1}. var json = JSON.parse('{"a":1}'); JSON.stringify(json); |
JSON Function Example
The following example uses a for
loop to print the IDs of each item in a JSON object and to print rows of dashes to represent null items.
json = {"menu": { "header": "SVG Viewer", "items": [ {"id": "Open"}, {"id": "OpenNew", "label": "Open New"}, null, {"id": "ZoomIn", "label": "Zoom In"}, {"id": "ZoomOut", "label": "Zoom Out"}, {"id": "OriginalView", "label": "Original View"}, null, {"id": "Quality"}, {"id": "Pause"}, {"id": "Mute"}, null, {"id": "Find", "label": "Find..."}, {"id": "FindAgain", "label": "Find Again"}, {"id": "Copy"}, {"id": "CopyAgain", "label": "Copy Again"}, {"id": "CopySVG", "label": "Copy SVG"}, {"id": "ViewSVG", "label": "View SVG"}, {"id": "ViewSource", "label": "View Source"}, {"id": "SaveAs", "label": "Save As"}, null, {"id": "Help"}, {"id": "About", "label": "About SVG Viewer..."} ] }}; print(json.menu.header); for (var i = 0; i < json.menu.items.length; i++) { if (json.menu.items[i] == null) { print("----"); } else { print(json.menu.items[i].id); } }
The output for this example is the following:
SVG ViewerOpenOpenNew----ZoomInZoomOutOriginalView----QualityPauseMute----FindFindAgainCopyCopyAgainCopySVGViewSVGViewSourceSaveAs----HelpAbout