Search code examples
javascriptjqueryjsonregexjsonp

How to add text to beginning and ending of JSON to make it JSONP


I'm working on a project, I can manually add a beginning name and parenthesis: bio( and an ending ) to the end of my JSON data to make it callable as JSONP.

I am going to do this to about 200 files which is why I'm trying to find a solution to do this in code.

I've tried using regex, converting to a string, trying to convert back, etc, and nothing seems to work.

My abbreviated JSON data is below:

{
"Directory": {
    "workbooks": ["/xl/workbook.xml"],
    "sheets": ["/xl/worksheets/sheet1.xml"],
    "style": "/xl/styles.xml",
    "defaults": {
        "xml": "application/xml",
        "rels": "application/vnd.openxmlformats-package.relationships+xml"
    }
},
"Workbook": {
    "AppVersion": [null],
    "Sheets": [
        [null]
    ],
    "CalcPr": [null],
    "xmlns": "http://schemas.openxmlformats.org/spreadsheetml/2006/main"
}

What I want is:

bio({  <--------
"Directory": {
    "workbooks": ["/xl/workbook.xml"],
    "sheets": ["/xl/worksheets/sheet1.xml"],
    "style": "/xl/styles.xml",
    "defaults": {
        "xml": "application/xml",
        "rels": "application/vnd.openxmlformats-package.relationships+xml"
    }
},
"Workbook": {
    "AppVersion": [null],
    "Sheets": [
        [null]
    ],
    "CalcPr": [null],
    "xmlns": "http://schemas.openxmlformats.org/spreadsheetml/2006/main"
}) <-------

I've gotten closest with Stringify and regex:

var myString = JSON.stringify(workbook);
var change = myString.replace(/^/,"bioInfo(").replace(/$/,")”);

When I try to change it back to an object so I can use it though, it fails saying: JSON.parse: unexpected character at line 1 column 1 of the JSON data

I've tried eval as well trying to get it to change back to an object but it just doesn't seem to work.

Hopefully my dilemma is clear and someone knows a good way to do this in Javascript or Jquery.

Thanks in advance.


Solution

  • You don't need anything as complicated as you are making it. Just concatenate your strings.

    var jsonp = "bio(" + json + ");"
    

    I've gotten closest with Stringify

    JSON is already a string. You only need to stringify something if you have a JavaScript data structure and want to convert it to JSON.