0

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);
3
  • your Jsons are not formatted correctly. Commented Jun 16, 2018 at 20:31
  • If it is a string, why would you stringify it?! Commented Jun 16, 2018 at 20:34
  • I think he meant to JSON.parse Commented Jun 16, 2018 at 20:34

1 Answer 1

1

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)

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.