Mohamed
Mohamed

Reputation: 49

Regex to filter json value

Hello Guys i want to get just two value from a big json array using regular expression. E.g: i have this json array

'{"data":"1233","image":"dsfsdfsdfds"."text":"hello world"."name": "java"}' '{"data":"1233df","image":"dsfsdfsdfsdfds"."text":"hello world"."name": "c#"}' '{"data":"1233sds","image":"dsfsdferesdfds"."text":"hello world"."name": "python"}' '{"data":"1sd233","image":"dsfsdfsdfrdfds"."text":"hello world"."name": "c++"}'

I want to get text and name value from this array using regular expression

Upvotes: 1

Views: 18304

Answers (3)

Aman Chhabra
Aman Chhabra

Reputation: 3894

You should not use regex for parsing JSON. Instead parse JSON through inbuilt functions like parse in case you are using Javascript or different libraries like GSON in case you are using JAVA.

Still, if there is any special requirement to use Regex here, you can use below:

1) For text:

.*?text"\s?:\s?"([\w\s]+)

Output :

Group 1 - 'hello world'

2) For name

.*?name"\s?:\s?"([\w\s]+)

Output:

Group 1 - java

Demo: https://regex101.com/r/74hOO1/1

-- EDIT --

If you want both text and name in one regex, you can use below one, provided text always come before name:

.*?text"\s?:\s?"([\w\s]+).*?name"\s?:\s?"([\w\s]+)

Output:

Group 1.    46-57   `hello world`
Group 2.    68-72   `java`

Demo: https://regex101.com/r/74hOO1/2

Upvotes: 4

Adsl Le
Adsl Le

Reputation: 111

You can use this regex :

"name"\s?+:\s?+"?([\w+#\s]+)"?

to extract its value here name for example

if you want other key for example text use text instead of name

"text"\s?+:\s?+"?([\w+#\s]+)"?

you'll find the value of the key in the first group See here https://regex101.com/r/1ZSUph/1

Upvotes: 0

Anshul Bansal
Anshul Bansal

Reputation: 1893

var data = '{"data":"1233","image":"dsfsdfsdfds", "text":"hello world", "name": "java"}';

var parsedData = JSON.parse(data);

var text = parsedData.text;
var name = parsedData.name;

Upvotes: 2

Related Questions