0

I have JSON data in the following format:

{"User":"aa2","Owner":"aa2_role","Status":"locked","Port":"5432","Description":"Transferred from CFS01 on Jun29","Project":"aa2","Server":"localhost"}

I can count on the key called "Project": to always be the same.

What I need is to pull the Value of the "Project": key which in this case is "aa2" using regex in JavaScript.

I have been trying different variations of /^("Project":)$/g but it is not working.

My last attempt I tried /[^"Project":$]/g but it gives me everything in the JSON Object but "Project":

Does anyone know how I can capture the value of a specific Project key?

EDIT: Just for clarification I agree with the use of the Parsing mechanism. My problem is that I am debugging/working with a previous code base that is using a separate function to pass the parsed JSON as a string into the function where now I need to pull the data needed from the string. After having spent this amount of time trying to come up with a work around I am about to scrap the function in order to use Parse... that's why I'm trying to use regex but the more I think about it, the more I realize that it's just bad code... but still, now I am just curious.

nasaQuant
  • 348
  • 1
  • 2
  • 8
  • 6
    Why not use `JSON.parse` to parse the JSON properly? – Ry- Jul 20 '17 at 05:59
  • `^` at the beginning of a *character group* (`[...]`) means *match everything **except** any of the following characters*. – Felix Kling Jul 20 '17 at 06:04
  • 1
    *"What I need is to pull the Value of the "Project": key .... using regex"* Why do you need to use a regular expression? – Felix Kling Jul 20 '17 at 06:05
  • JSON stands for "JavaScript Object Notation", so obviously javascript has it's ways to handle those without resorting to regex. But if you're curious about the regex, it would be more like `/"(?:Project)":"(\w*)"/g`. You could try it out in an online regex tester like for example [this one](http://regexr.com/) – LukStorms Jul 20 '17 at 07:27

2 Answers2

2

No need to use Regular expression to extract value from object string. Just Use JSON.parse(). This will convert string to Object. After parsing you can use key to access the value.

var obj = JSON.parse('{"User":"aa2","Owner":"aa2_role","Status":"locked","Port":"5432","Description":"Transferred from CFS01 on Jun29","Project":"aa2","Server":"localhost"}');

console.log(obj.Project);
Dinesh undefined
  • 5,490
  • 2
  • 19
  • 40
1

Parse the JSON and then get the value. Working example : https://jsfiddle.net/vineeshmp/2c8z7r6u/

var json =' {"User":"aa2","Owner":"aa2_role","Status":"locked","Port":"5432","Description":"Transferred from CFS01 on Jun29","Project":"aa2","Server":"localhost"}';    
json = JSON.parse(json);
alert(json.Project);
Vineesh
  • 3,762
  • 20
  • 37