0

I have an HTML dropdown for an InDesign script that when I pull the JSON from the file into, it comes back as object Object. i cannot figure out what i am doing wrong.

I've tried a bunch of answers on here, but none are working with the code I have.

my HTML:

<h4>Design Tools</h4>

    <select id="swatchNumber" onchange="swatchIndex()" class="custom-select"></select>

my jsx:

function swatchIndex() {  
    var doc, swatches, json, n, l, swatch;  
    doc = app.activeDocument;  
    swatches = doc.swatches;  
    json = [];  
    l = swatches.length;  
    for (n = 0; n < l; n++) {  
        swatch = swatches[n];  
        json[n] = '"' + n + '": {' +  
            '"name": "' + swatch.name + '"}' 
    }  
    // prepare the JSON as a string  
    json = '{' + json.join(',') + '}';  
    return json;  
}

my javascript:

var callBack = function (result) {
    try {
        var swatchesConv = JSON.parse(result);

        var select = document.createElement('SELECT');
        select.name="swatchNumber";
        select.id="swatchNumber";
        document.body.appendChild(select);

        Object.keys(swatchesConv).forEach(function(result){
        document.getElementById('swatchNumber').innerHTML +='<option value="'+result+'">'+swatchesConv[result]+'</option>'
        })

        alert(result);

    } catch (e) { alert(e.message); }
//         alert("Wrong");
}
csInterface.evalScript('swatchIndex()', callBack);

the actual JSON that pops into my alert(result): {“0”: {“name”: “None”}, “1”: {“name”: “Registration”), “2”: {“name”: “Paper”}, “3”: {“name”: “Black”}}

when I load the application I get the alert to pop up the JSON but the dropdown shows the right amount but each index just says object Object

1 Answer 1

2

Since swatchesConv is

{
 “0”: {“name”: “None”}, 
 “1”: {“name”: “Registration”), 
 “2”: {“name”: “Paper”}, 
 “3”: {“name”: “Black”}
}

the result in Object.keys(swatchesConv).forEach will be the keys, but the value of swatchesConv[result] will be the object of the key. So, for the key 0 it would be {“name”: “None”}.

To display the name, you have to use:

'<option value="'+result+'">'+swatchesConv[result].name+'</option>'

or

'<option value="'+result+'">'+swatchesConv[result]['name']+'</option>'

when creating the options of the select.

Sign up to request clarification or add additional context in comments.

2 Comments

thanks so much! the [name] didn't work but the [result].name did! I need to find time to learn json and how to parse! Thanks for everything!
Fixed the typo.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.