-1

I have the following JSON and I want to get the name 'Ethan Richardson' from the array photographer_name into a variable.

I have tried to use regex but I could not get that to work.

So what I want is to be left with a variable like let name = 'Ethan Richardson'

The JSON structure is below:

{
    "eventName": "Hilton Hotel",
    "photographer_name": ["Ethan Richardson"],
    "image_url": "https://s-media-cache-ak0.pinimg.com/originals/a0/b8/b6/a0b8b6b2e9b077a8ac7791455f83a27b.jpg",
    "subtitle": "Enjoy the night",
    "result": "1"
}
fernandosavio
  • 9,849
  • 4
  • 24
  • 34
Ethan Richardson
  • 461
  • 2
  • 10
  • 28

3 Answers3

1
var json = JSON.parse('{"eventName":"Hilton Hotel","photographer_name":["Ethan Richardson"],"image_url":"https://s-media-cache-ak0.pinimg.com/originals/a0/b8/b6/a0b8b6b2e9b077a8ac7791455f83a27b.jpg","subtitle":"Enjoy the night","result":"1"}');
var variable = json.photographer_name[0];
Necky
  • 70
  • 8
0
const jsonString = '{"eventName":"Hilton Hotel","photographer_name":["Ethan Richardson"],"image_url":"https://s-media-cache-ak0.pinimg.com/originals/a0/b8/b6/a0b8b6b2e9b077a8ac7791455f83a27b.jpg","subtitle":"Enjoy the night","result":"1"}'
const jsonObject = JSON.parse(jsonString)
const name = jsonObject.photographer_name[0]

Please never try to come up with custom parsing solutions, if tested and working ones exists

Balázs Édes
  • 13,452
  • 6
  • 54
  • 89
  • You shouldn't use JSON.parse without an `try ... catch` – cyr_x Feb 01 '17 at 12:14
  • And what should I do in catch? Not related to the question. – Balázs Édes Feb 01 '17 at 12:14
  • handle the error or rethrow it to handle it on top level – cyr_x Feb 01 '17 at 12:15
  • Don't want to argue about it, but it's way out of the scope of the question how parsing errors are handled. – Balázs Édes Feb 01 '17 at 12:17
  • Sure but if he should use Json.parse, he should know about it ;) – cyr_x Feb 01 '17 at 12:18
  • @BalázsÉdes simple solution. Add the relevant documentation for the OP to read about `JSON.parse()` https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse Adding the relevant references is always a bonus for anyone who might stumble on this quesiton seeking help and is new to any of this. – NewToJS Feb 01 '17 at 12:23
0

You need to parse it first with JSON.parse

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned.

and then take photographer_name as key.

var json = '{"eventName":"Hilton Hotel","photographer_name":["Ethan Richardson"],"image_url":"https://s-media-cache-ak0.pinimg.com/originals/a0/b8/b6/a0b8b6b2e9b077a8ac7791455f83a27b.jpg","subtitle":"Enjoy the night","result":"1"}',
    object = JSON.parse(json),
    name = object.photographer_name;

console.log(name);
 
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392