-1

I am trying to get json object from another js file. I found out the end result is json in string form look like this

"[{ "part": "Part1", "dwg": "ASAD" }, { "part": "Part2", "dwg": "B" }];" 

How can I convert into JSON object? Here is my code

var jsonData = $.get("/Scripts/dummy.js", function (data) {

            console.log(data);
            return data;
        });
Ammar Khan
  • 2,565
  • 6
  • 35
  • 60

4 Answers4

0

use JSON.stringify().

var json = JSON.stringify(data);

Alex_B
  • 838
  • 7
  • 13
0

To convert a string to JSON object, use JSON.parse:

var jsonObject = JSON.parse(jsonText);

var jsonData = $.get("/Scripts/dummy.js", function (data) {

        console.log(data);
        return  JSON.parse(data);
    });
Aram Gevorgyan
  • 2,175
  • 7
  • 37
  • 57
0

what you need is JSON.parse():

var json = '[{ "part": "Part1", "dwg": "ASAD" }, { "part": "Part2", "dwg": "B" }]';
JSON.parse(json); 
Alex Shilman
  • 1,547
  • 1
  • 11
  • 15
0

First you'll need to remove the trailing the ; from your object string and use proper single/double quote wrapping:

// Your string used all double quotes, replace the outermost quotes with single 
// quotes as shown below. Also notice that the ; has been moved outside the 
// string, semicolons are not permitted as part of JSON object strings
var x = '[{ "part": "Part1", "dwg": "ASAD" }, { "part": "Part2", "dwg": "B" }]';    

and then use JSON.parse() to return a valid JSON object:

JSON.parse(x);
=> [ { part: 'Part1', dwg: 'ASAD' },
     { part: 'Part2', dwg: 'B' } ]
wvandaal
  • 4,265
  • 2
  • 16
  • 27