Romarie
Romarie

Reputation: 958

Javascript Regex to match key value of JSON

I am not really good at regex so I would be grateful if you help me >.<

From my mqtt server, I have this 2 different types of JSON data received.

{"type":"aaa","id":"123abc","data":[0.0000,0,1]}

and

{"data":[0430be588a3700000000000058883700000000]}

and what I want is to capture the value of 'data' from these 2 input types where I can see the ff. output

"data":[0.0000,0,1]
"data":[0430be588a37000000]

I tried the ff. regex to do this

/"([_a-z]\w*)":\s*([^,]*)/g

Check here: https://regex101.com/r/zmeFRR/1

However, what I received is

[0.0000

and

[0430be588a3700000000000058883700000000]}

Can someone help me try to resolve this?

PS. I tried to use JSON.parse on this data since I thought it would be easier to parse data, but because of the type of data I received, data":[0430be588a37000000], this won't do. That's why I tried regex instead.

Upvotes: 2

Views: 1731

Answers (1)

The fourth bird
The fourth bird

Reputation: 163362

Using the negated character class in the capture group ([^,]*) matches 0+ times any char except a comma, which can not cross matching the comma in 0.0000,0,1

You could get either the value between double quotes, or the value between the square brackets:

"([_a-z]\w*)":\s*("[^"]*"|\[[^]\[]*])
  • " Match "
  • ([_a-z]\w*) Capture group 1, match a single char being either _ or a-z followed by optional word chars
  • ":\s* Match ": and optional whitespace chars
  • ("[^"]*"|\[[^]\[]*]) Capture group 2, match either from ".." or [..]

Regex demo

Upvotes: 2

Related Questions