mm1975
mm1975

Reputation: 1655

Create a nested JSON Object with Javascript

I´d like to create a JSON-Object for a Google API-Request. Only content is needed to change. My solution gives me an invalid JSON-Format and is more a hack. Is there an easier way to do this? Thank your for your hints.

The necessary format look like this:

{
  "requests": [
    {
      "image": {
        "content": "/9j/7QBEUGhvdG9zaG9...base64-encoded-image-content...fXNWzvDEeYxxxzj/Coa6Bax//Z"
      },
      "features": [
        {
          "type": "DOCUMENT_TEXT_DETECTION"
        }
      ]
    }
  ]
}

JS

var cvs = cvs.substring('data:image/png;base64,'.length);

var json1 = '{"requests":[{  "image":{    "content":"'
var json2 = '"},  "features": [{"type":"DOCUMENT_TEXT_DETECTION"}]    } ]}'

var entireJson = json1 + cvs + json2;
var ocrImage = JSON.stringify(entireJson);

Upvotes: 0

Views: 953

Answers (1)

Attersson
Attersson

Reputation: 4876

What you have done in your example is initializing a Javascript Object.

JSON.parse(object_string); is not necessary. You may initialize it directly:

var ocrImage = {
  "requests": [
    {
      "image": {
        "content": "/9j/7QBEUGhvdG9zaG9...base64-encoded-image-content...fXNWzvDEeYxxxzj/Coa6Bax//Z"
      },
      "features": [
        {
          "type": "DOCUMENT_TEXT_DETECTION"
        }
      ]
    }
  ]
}

console.log(ocrImage)

Upvotes: 1

Related Questions