-1

I would like to extract a JSON string within another string.

Currently I am getting the full string using file_get_contents and running the following pattern on the string: https://regex101.com/r/5jAucO/1 which pretty much gives multiple matches.

I would like to extract the JSON string that is saved in window._sharedData but haven't been able to achieve that. Does someone have any idea how I could do that?

1

1 Answer 1

0

Why not include _sharedData in the regex like? _sharedData\s*=\s*\{.+\}

  • or with lookbehind: (?<=_sharedData\s=)\s*\{.+\}

  • or take the json from a capturing group: _sharedData\s*=\s*(\{.+\})

One concern with the lookbehind is if they add an additional whitespace character between _sharedData and = it won't match.

This only works well since there are no linebreaks in the JSON.

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

2 Comments

can we do the same thing using javascript ? i want to get _sharedData using javascript
the regex with the lookbehind wouldn't work in javascript but since the example is trying to capture json within a web page, I would recommend making sure the html is rendered in a dom and then just access the _sharedData variable via window._sharedData instead.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.