1

I have a web API that returns the following JSON:

[{"MovieId":2,"Title":"End Game","Year":"2013","Actors":"Cuba Gooding Jr., Angie Harmon, James Woods, Patrick Fabian","Plot":"A secret Service agent and a news reporter investigate the conspiracy behind the assassination of the President","Director":"Andy Cheng","Cover":"Endgame-movie-cover.jpg"},{"MovieId":3,"Title":"Saving Private Ryan","Year":"1998","Actors":"Tom Hanks, Tom Sizemore, Edward Burns, Barry Pepper","Plot":"Following the Normandy Landings, a group of U.S. soldiers go behind enemy lines to retrieve a paratrooper whose brothers have been killed in action","Director":"Steven Spielberg","Cover":"Saving-Private-Ryan-Cover.jpg"}]

I want to pass JSON from the response to jqGrid to populate the data in a table, after my AJAX call which looks as follows:

function fetchMovies(){
    $.ajax({
        url: 'http://orionadmin.azurewebsites.net/api/movies',
        type: 'GET',
        datatype: 'JSON',
        contentType: 'application/json',
        success: function (data) {
            grid_data1 = JSON.stringify(data);
            alert(grid_data);
        },
        error: function (x, h, r) {
            alert('Something went wrong')
        }
    });
}

My result from the AJAX call looks as follows:

"[{"MovieId":2,"Title":"End Game","Year":"2013","Actors":"Cuba Gooding Jr., Angie Harmon, James Woods, Patrick Fabian","Plot":"A secret Service agent and a news reporter investigate the conspiracy behind the assassination of the President","Director":"Andy Cheng","Cover":"Endgame-movie-cover.jpg"},{"MovieId":3,"Title":"Saving Private Ryan","Year":"1998","Actors":"Tom Hanks, Tom Sizemore, Edward Burns, Barry Pepper","Plot":"Following the Normandy Landings, a group of U.S. soldiers go behind enemy lines to retrieve a paratrooper whose brothers have been killed in action","Director":"Steven Spielberg","Cover":"Saving-Private-Ryan-Cover.jpg"}]"

This is the format jqGrid takes, to populate data in the table:

<script type="text/javascript">
    var grid_data = 
    [ 
        {id:"1",name:"Desktop Computer",note:"note",stock:"Yes",ship:"FedEx", sdate:"2007-12-03"},
        {id:"2",name:"Laptop",note:"Long text ",stock:"Yes",ship:"InTime",sdate:"2007-12-03"},
        {id:"3",name:"LCD Monitor",note:"note3",stock:"Yes",ship:"TNT",sdate:"2007-12-03"},
        {id:"4",name:"Speakers",note:"note",stock:"No",ship:"ARAMEX",sdate:"2007-12-03"},
        {id:"5",name:"Laser Printer",note:"note2",stock:"Yes",ship:"FedEx",sdate:"2007-12-03"},
        {id:"6",name:"Play Station",note:"note3",stock:"No", ship:"FedEx",sdate:"2007-12-03"},
        {id:"7",name:"Mobile Telephone",note:"note",stock:"Yes",ship:"ARAMEX",sdate:"2007-12-03"},
        {id:"8",name:"Server",note:"note2",stock:"Yes",ship:"TNT",sdate:"2007-12-03"},
        {id:"9",name:"Matrix Printer",note:"note3",stock:"No", ship:"FedEx",sdate:"2007-12-03"},
        {id:"10",name:"Desktop Computer",note:"note",stock:"Yes",ship:"FedEx", sdate:"2007-12-03"},
        {id:"11",name:"Laptop",note:"Long text ",stock:"Yes",ship:"InTime",sdate:"2007-12-03"},
        {id:"12",name:"LCD Monitor",note:"note3",stock:"Yes",ship:"TNT",sdate:"2007-12-03"},
        {id:"13",name:"Speakers",note:"note",stock:"No",ship:"ARAMEX",sdate:"2007-12-03"},
        {id:"14",name:"Laser Printer",note:"note2",stock:"Yes",ship:"FedEx",sdate:"2007-12-03"},
        {id:"15",name:"Play Station",note:"note3",stock:"No", ship:"FedEx",sdate:"2007-12-03"},
        {id:"16",name:"Mobile Telephone",note:"note",stock:"Yes",ship:"ARAMEX",sdate:"2007-12-03"},
        {id:"17",name:"Server",note:"note2",stock:"Yes",ship:"TNT",sdate:"2007-12-03"},
        {id:"18",name:"Matrix Printer",note:"note3",stock:"No", ship:"FedEx",sdate:"2007-12-03"},
        {id:"19",name:"Matrix Printer",note:"note3",stock:"No", ship:"FedEx",sdate:"2007-12-03"},
        {id:"20",name:"Desktop Computer",note:"note",stock:"Yes",ship:"FedEx", sdate:"2007-12-03"},
        {id:"21",name:"Laptop",note:"Long text ",stock:"Yes",ship:"InTime",sdate:"2007-12-03"},
        {id:"22",name:"LCD Monitor",note:"note3",stock:"Yes",ship:"TNT",sdate:"2007-12-03"},
        {id:"23",name:"Speakers",note:"note",stock:"No",ship:"ARAMEX",sdate:"2007-12-03"}
    ];

How do I maintain the original JSON format without the " " after the AJAX call, so that I can get my data displayed in my jqGrid?

honk
  • 9,137
  • 11
  • 75
  • 83
Frank Odoom
  • 1,545
  • 18
  • 19
  • Are you just talking about the quotes around the outer square brackets? Don't stringify it. Why are you calilng `JSON.stringify(data)`? Please [edit] your question to show how you're actually trying to use `data` with JqGrid. Does JqGrid expect JSON (a *string*), or does it expect an object? – nnnnnn Dec 22 '16 at 01:28
  • when i don't use .stringify() i get [object, Object] returned – Frank Odoom Dec 22 '16 at 01:38
  • JqGrid expects it like the Original Json Response from the Api – Frank Odoom Dec 22 '16 at 01:39
  • `[object, Object]` is just what appears in the alert because `data` contains an object (actually, an array). JqGrid should be fine with that, so again, please [edit] your question to show how you're using it with JqGrid. – nnnnnn Dec 22 '16 at 01:40
  • I doubt jqGrid expects JSON - it expects a javascript object, which you have as `data` - Oh, and when you stringify it, it becomes a string, so the extra `"` in the alert are misleading ... just use data, you'll be golden (and realise that data is not JSON, it's an object that was created from a JSON string for you by $.ajax - trust me, jqGrid likes objects, not a string – Jaromanda X Dec 22 '16 at 01:49
  • your server `orionadmin.azurewebsites.net` responds with `Content-Type: text/html; charset=utf-8` though – Jaromanda X Dec 22 '16 at 01:53
  • ok Jaromanda i tried data and still no tables but if i hard code the table data with the api response i get my data populated, hmm.. very tricky – Frank Odoom Dec 22 '16 at 02:01
  • is it a Cross Origin request? or is the request coming from a page served by the domain `http://orionadmin.azurewebsites.net/` - if not, you have a CORS issue you need to fix on the `orionadmin.azurewebsites.net` server - also, the API should return a response header with `Content-type: application/json` rather than `text/html` – Jaromanda X Dec 22 '16 at 02:26
  • I am returning Json now and all requests are being served from the same domain – Frank Odoom Dec 22 '16 at 02:31

4 Answers4

1

Maybe something like this?

'[{"MovieId":2,"Title":"End Game","Year"...'.replace(new RegExp('"', 'g'), '')
Marko Milojevic
  • 731
  • 7
  • 12
1

You don't need JSON.stringify(), your data is already in json format

Taki
  • 17,320
  • 4
  • 26
  • 47
  • 2
    are you saying data is already a JSON string? - because, it isn't, it's a javscript object – Jaromanda X Dec 22 '16 at 01:49
  • JqGrid is expecting an object and you're converting it to a string, try console.log(data); to see if you have the right format – Taki Dec 22 '16 at 01:55
0

JSON is basically a format where you pass Javascript as a string. JQuery actually parses the string into an object, which is what you want. But you are then transforming the object into JSON again, which is a string, but what you really want to use is the object. TL;DR: Don't stringify it

iagowp
  • 2,428
  • 1
  • 21
  • 32
0

You can use addRowData method of JqGrid. it expects an object as input, since your result is an array of objects you just need to loop through the array and add Row Data

var data = [{"MovieId":2,"Title":"End Game","Year":"20113","Actors":"Cuba Gooding Jr., Angie Harmon, James Woods, Patrick Fabian","Plot":"A secret Service agent and a news reporter investigate the conspiracy behind the assassination of the President","Director":"Andy Cheng","Cover":"Endgame-movie-cover.jpg"},{"MovieId":3,"Title":"Saving Private Ryan","Year":"1998","Actors":"Tom Hanks, Tom Sizemore, Edward Burns, Barry Pepper","Plot":"Following the Normandy Landings, a group of U.S. soldiers go behind enemy lines to retrieve a paratrooper whose brothers have been killed in action","Director":"Steven Spielberg","Cover":"Saving-Private-Ryan-Cover.jpg"},{"MovieId":4,"Title":"Cobra","Year":"1986","Actors":"Sylvester Stallone, Brigitte Nielsen, Reni Santoni, Andrew Robinson","Plot":"A tough-on-crime street cop must protect the only surviving witness to a strange murderous cult with far reaching plans","Director":"George P. Cosmatos","Cover":"cobra.jpg"},{"MovieId":5,"Title":"Savages","Year":"2012","Actors":"Blake Lively, Taylor Kitsch, Aaron Taylor-Johnson, Jana Banker","Plot":"Pot growers Ben and Chon face off against the Mexican drug cartel who kidnapped their shared girlfriend","Director":"Oliver Stone","Cover":"savages.jpg"},{"MovieId":6,"Title":"The Man in the Iron Mask","Year":"1998","Actors":"Leonardo DiCaprio, Jeremy Irons, John Malkovich, Gérard Depardieu","Plot":"The cruel King Louis XIV of France has a secret twin brother who he keeps imprisoned. Can the twin be substituted for the real king?\"","Director":"Randall Wallac","Cover":"maninimask.jpg"},{"MovieId":7,"Title":"The Shawshank Redemption","Year":"1994","Actors":"Tim Robbins, Morgan Freeman, Bob Gunton, William Sadler","Plot":"Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.","Director":"Frank Darabont","Cover":"MV5BODU4MjU4NjIwNl5BMl5BanBnXkFtZTgwMDU2MjEyMDE@._V1_SX300.jpg"},{"MovieId":8,"Title":"Perfume: The Story of a Murderer","Year":"2006","Actors":"Ben Whishaw, Francesc Albiol, Gonzalo Cunill, Roger Salvany","Plot":"Jean-Baptiste Grenouille, born with a superior olfactory sense, creates the world's finest perfume. His work, however, takes a dark turn as he searches for the ultimate scent.","Director":"Tom Tykwer","Cover":"MV5BMTI0NjUyMTk3Nl5BMl5BanBnXkFtZTcwOTA5MzkzMQ@@._V1_SX300.jpg"},{"MovieId":9,"Title":"Catch Me If You Can","Year":"2002","Actors":"Leonardo DiCaprio, Tom Hanks, Christopher Walken, Martin Sheen","Plot":"The true story of Frank Abagnale Jr. who, before his 19th birthday, successfully conned millions of dollars' worth of checks as a Pan Am pilot, doctor, and legal prosecutor.","Director":"Steven Spielberg","Cover":"MV5BMTY5MzYzNjc5NV5BMl5BanBnXkFtZTYwNTUyNTc2._V1_SX300.jpg"},{"MovieId":10,"Title":"James Bond 007","Year":"2003","Actors":"Pierce Brosnan, John Cleese, Willem Dafoe, Judi Dench","Plot":"MI6 agent James Bond:007 rushes into action to rescue Oxford scientist Katya Nadanova from a terrorist facility in Egypt. After rescuing Katya bond heads to a mining town in Peru to ..","Director":"Scot Bayless","Cover":"007.jpg"},{"MovieId":11,"Title":"The Mask","Year":"1994","Actors":"Jim Carrey, Peter Riegert, Peter Greene, Amy Yasbeck","Plot":"Bank clerk Stanley Ipkiss is transformed into a manic superhero when he wears a mysterious mas","Director":"Chuck Russel","Cover":"theMask.jpg"},{"MovieId":12,"Title":"Rambo","Year":"2008","Actors":"Sylvester Stallone, Julie Benz, Matthew Marsden, Graham McTavish","Plot":"In Thailand, John Rambo joins a group of missionaries to venture into war-torn Burma, and rescue a group of Christian aid workers who were kidnapped by the ruthless local infantry unit","Director":"Sylvester Stallone","Cover":"rambo.jpg"},{"MovieId":13,"Title":"The Green Mile","Year":"1999","Actors":"Tom Hanks, David Morse, Michael Clarke Duncan, Bonnie Hunt\",\"Plot\":\"The lives of guards on Death Row are affected by one of their charges: a black man accused of child murder and rape, yet who has a mysterious gift","Plot":"The lives of guards on Death Row are affected by one of their charges: a black man accused of child murder and rape, yet who has a mysterious gift.\",\"Language\":\"English, French\",\"Country\":\"USA\",\"Awards\":\"Nominated for 4 Oscars. Another 15 wins & 30 nominations","Director":"Frank Darabont","Cover":"greenmile.jpg"}]
$("#grid").jqGrid({
    datatype: "local",
    height: 250,
    colNames: ['MovieId', 'Title', 'Title', 'Actors', 'Plot','Director'],
    colModel: [{
        name: 'MovieId',
        index: 'MovieId',
        width: 60,
    search:false},
    {
        name: 'Title',
        index: 'Title',
        width: 120,
    search:false},
    {
        name: 'Year',
        index: 'Year',
        width: 60,
    search:false},
    {
        name: 'Actors',
        index: 'Actors',
        width: 120,
    search:false},
    {
        name: 'Plot',
        index: 'Plot',
        width: 120,
    search:false},
    {
        name: 'Director',
        index: 'Director',
        width: 120,
        search:false}
    ],
    caption: "IMDB"
});

for (var i = 0; i <= data.length; i++) {
   $("#grid").jqGrid('addRowData', i + 1, data[i]);
}
<link href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.14/themes/base/jquery-ui.css" rel="stylesheet"/>
<link href="https://cdn.jsdelivr.net/free-jqgrid/4.13.5/css/ui.jqgrid.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<script src="https://cdn.jsdelivr.net/free-jqgrid/4.13.5/js/jquery.jqgrid.min.js"></script>

<table id="grid"></table>
Deep
  • 9,594
  • 2
  • 21
  • 33