-2

I have the following string returned from a server:

{"href":"about:blank#&executeFunction<-finishedStroke&&arguments<-{\"base64DataUrl\":\"data:image/png;base64,iVBORw0KGgoAAErkJggg==\"}&"}

I want to extract data:image/png;base64,iVBORw0KGgoAAErkJggg== (the base64DataURL part) from it. What's the best way to do this with Javascript?

Please note that I am asking how to parse values from JSON. This is not the same as this question, which asks how to extract fields from nested objects and arrays.

What I've tried: I have tried

JSON.parse(<string>).href.split('base64DataUrl":"')[1].split('"')[0]

which yields the right answer, but I'm hoping for a more concise solution.

Phil
  • 157,677
  • 23
  • 242
  • 245
gkeenley
  • 6,088
  • 8
  • 54
  • 129
  • @Phil Do you know if there's a way for me to remove the duplicate tag? I edited the question to specify that it's not the same as the other question, but the duplicate tag is still there. – gkeenley Apr 30 '21 at 03:07
  • It's not really enough to only say _"this is not the same"_. You should also explain why. In any case, I've re-opened this but you should still provide an explanation. And while you're editing your question, you should also show what you've tried – Phil Apr 30 '21 at 03:14
  • So wait, your one-line solution works but you're after something better? I'm really failing to see why this is a question – Phil Apr 30 '21 at 03:33
  • That's right, even though my solution is one line, I'm interested to know if there's a solution that doesn't have as many chained functions. – gkeenley Apr 30 '21 at 04:11

3 Answers3

1

Since the server is not returning valid JSON, you will have to parse it with indexOf and substring.

let y = stringFromServer; 
let a = y.indexOf('data:'); 
let b = y.indexOf('\"}',a); 
let dataUrl = y.substring(a,b);
Walter Stabosz
  • 7,447
  • 5
  • 43
  • 75
1

This is JSON, but the part you're interested in isn't exposed as part of the object. So I would suggest that you just consider it a string and use a string-parsing method, like a regular expression.

const string = `{"href":"about:blank#&executeFunction<-finishedStroke&&arguments<-{\"base64DataUrl\":\"data:image/png;base64,iVBORw0KGgoAAErkJggg==\"}&"}`;

const dataURL = /"base64DataUrl":"(.*?(?="))/gm.exec(string)[1];
console.log(dataURL);
matthew-e-brown
  • 2,837
  • 1
  • 10
  • 29
1

Here is my try


let sample = {"href":"about:blank#&executeFunction<-finishedStroke&&arguments<-{\"base64DataUrl\":\"data:image/png;base64,iVBORw0KGgoAAErkJggg==\"}&"}

let splitter = sample.href.split("<-")

console.log(JSON.parse(splitter[2].substring(0, splitter[2].length - 1))["base64DataUrl"]
)
Sudarshan
  • 702
  • 6
  • 24