ECMA Script SP.ClientContext to Json

Posted on Updated on

Want to convert to Json a list.getItems collection? this is the way using ECMA Javascript

Declare SP.js

<SharePoint:ScriptLink runat="server" Name="SP.js" Localizable="false" OnDemand="False" LoadAfterUI="True"></SharePoint:ScriptLink> 

 

JavaScript Function

function getJson() {
    var context = new SP.ClientContext("/");
    var list = context.get_web().get_lists().getByTitle("YourList"); 
    var viewXml = "<View><RowLimit>1000</RowLimit></View>";
    var query = new SP.CamlQuery();
    query.set_viewXml(viewXml);
    var items = list.getItems(query);
    context.load(items, "Include(Column1,Column2,Column3)");

    function onLoaded() {
        var myItems = [];
        var itemsCount = items.get_count();
        for (var i = 0; i < itemsCount; i++) {
            var item = items.itemAt(i);
            var myItem = JSON.stringify(item.get_fieldValues());
            myItems.push(myItem);
        }
        alert(myItems);
    }

    context.add_requestSucceeded(onLoaded);

    function onFailure() {

    }

    context.add_requestFailed(onFailure);
    context.executeQueryAsync();
} 
 
UPDATE
 
In order to use JSON.parse() you must change the [Object<Array>] like this
 
var dt = "[" + MyItems + "]";
var ret = JSON.parse(MyItems); 

It will give you a [Object],[Object],[Object]

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s