Kin
Kin

Reputation: 4596

How to get JSON data from the text?

I have a string, something like this:

sometext{"points":{"point":[{"lat":"55.68705772049725","lon":"21.127218855544925"},{"lat":"55.68714472465217","lon":"21.127141742035747"},{"lat":"55.6871934235096","lon":"21.12712439149618"},{"lat":"55.68733625113964","lon":"21.127151465043426"},{"lat":"55.68751168437302","lon":"21.12717761658132"},{"lat":"55.687646800652146","lon":"21.127120200544596"},{"lat":"55.68781033158302","lon":"21.127034788951278"},{"lat":"55.687981490045786","lon":"21.12691568210721"}]}}sometext

Is it possible with regex extract JSON in Javascript?

P.S. I get a lot of data and joining it in to the string. So i need to get json from that string as there can be the end of firs object and the beginning of other

Upvotes: 2

Views: 147

Answers (2)

mikach
mikach

Reputation: 2427

var str = 'sometext{"points":{"point":[{"lat":"55.68705772049725","lon":"21.127218855544925"},{"lat":"55.68714472465217","lon":"21.127141742035747"},{"lat":"55.6871934235096","lon":"21.12712439149618"},{"lat":"55.68733625113964","lon":"21.127151465043426"},{"lat":"55.68751168437302","lon":"21.12717761658132"},{"lat":"55.687646800652146","lon":"21.127120200544596"},{"lat":"55.68781033158302","lon":"21.127034788951278"},{"lat":"55.687981490045786","lon":"21.12691568210721"}]}}sometext';

var object = JSON.parse(str.match(/({.*})/).pop());

Upvotes: 1

Denys Séguret
Denys Séguret

Reputation: 382150

Supposing you don't have braces outside of the JSON part, and supposing that what is encoded is an object as in your example (not an array), then you may do

var obj = JSON.parse(s.match(/({.*})/)[1]);

If you have braces outside, you'll have to look for a more reliable way to detect the start and end of the JSON part.

Upvotes: 5

Related Questions