Skip to content

Instantly share code, notes, and snippets.

@kvendrik
Last active August 29, 2015 14:23
Show Gist options
  • Select an option

  • Save kvendrik/e69d30afa0a071f934d7 to your computer and use it in GitHub Desktop.

Select an option

Save kvendrik/e69d30afa0a071f934d7 to your computer and use it in GitHub Desktop.
Sketch JSON Parser
var doc = context.document,
app = [NSApplication sharedApplication],
jsonStr = [doc askForUserInput:"Enter the JSON you'd like to use" initialValue:""],
json;
try {
json = JSON.parse(jsonStr);
} catch(e){
[app displayDialog:"Whoops, looks like that's not valid JSON."]
return;
}
var selectedLayers = context.selection,
selectedCount = selectedLayers.count(),
getValByPath = function(path){
var pieces = path.split('.'),
currPath = json;
for(var i = 0; i < pieces.length; i++){
var val = pieces[i];
if(currPath[val] == undefined){
return undefined;
} else {
currPath = currPath[val];
}
}
return currPath;
};
if(selectedCount == 0) {
[app displayDialog:"No layers are selected."]
} else {
for(var i = 0; i < selectedCount; i++){
var layer = selectedLayers[i],
tagMatch = layer.name().match(/\$([^\s]+)/),
tagVal = tagMatch ? tagMatch[1].trim() : '';
if(!tagVal) continue;
switch(layer.class()){
case MSTextLayer:
var val = getValByPath(tagVal);
if(val){
layer.setStringValue(String(val));
layer.adjustFrameToFit();
}
break;
case MSBitmapLayer:
log('it\'s an image');
break;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment