Transform Javascript code to JSON and vice versa

2019-09-09 07:59发布

问题:

I'm working on a small project in which I will work with dgrid dojo, the dgrid must be customized according to the profile of the person if he's administrator or simple user. The dgrid will be filled from a REST service, and I had the idea to not only fill the dgrid but also customize it with textbox, buttons and checkbox.

For example here is the code of a dgrid with 2 columns whose fields can not be changed:

window.Grid= new StandardGrid({
    sort: "abbreviation",
    store: stateStore(),
    columns: {
           abbreviation: 'Abbreviation',
           name: 'Name'
    }
}, "MyGrid");

the service must verify if the person is an administrator and if so send in JSON Format the settings to add more features to dgrid, by changing "columns" with :

[ editor({
    label: "Abbreviation",
    field: "abbreviation",
    editor: "text",
    editOn: "dblclick"
}),
editor({
    label: "Name",
    field: "name",
    editor: "text",
    editOn: "dblclick"
})]

I want to send this configuration code in json format. I want to know if this is workable and if so, how? Thank you

回答1:

Since functions aren't a valid part of JSON, you'd need to do some amount of processing to go between JSON and dgrid column plugins. For example, in the case of editor, you could just test each object for presence of the editor property, and if found, apply the editor function around it when you actually create the column structure from your JSON.



回答2:

I'm not sure regarding Dojo. But if you want to convert a JS Object to JSON then simply:

var jsonString = JSON.stringify(objectGoesHere);