Search code examples
javascriptjsonstringsubstring

How to pull out a portion from long string of metadata


This is my first time working with very long metadata in an api response. I would like to dig into the metadata and only pull out the image_url. I am wondering if there is an easier way to do so than splicing this extremely long string a bunch of times. In this example here is the metadata:

"metadata": "{\"id\":4647,\"name\":\"Pancake\",\"generation\":10,\"created_at\":\"2017-11-24T09:35:05.000Z\",\"birthday\":\"2017-11-24T00:00:00.000Z\",\"image_url\":\"https://img.cryptokitties.co/0x06012c8cf97bead5deae237070f9587f8e7a266d/4647.svg\",\"image_url_cdn\":\"https://img.cn.cryptokitties.co/0x06012c8cf97bead5deae237070f9587f8e7a266d/4647.svg\",\"color\":\"mintgreen\",\"kitty_type\":null,\"is_fancy\": .... etc

I only want the portion of the very long metadata string for image_url that is "https://img.cryptokitties.co/0x06012c8cf97bead5deae237070f9587f8e7a266d/4647.svg"

Any suggestions on what is the most efficient way to achieve this?

I tried How can we extract specific part of the string from long string? solution but I have lots of objects in my json response so I would need to iterate over everything and use a while loop. It seemed overly complicated.


Solution

  • You can use JSON.parse() on the metadata string to get a JavaScript object. From that you can just index the object with the image_url key.

    Example:

    const metadata = JSON.parse(response['metadata'])
    const imageUrl = metadata['image_url'];