Learn business growth with Google Analytics 4 Forums Google Analytics 4 Extract pure JSON data using Google Analytics Data API v1 runReport

  • Extract pure JSON data using Google Analytics Data API v1 runReport

    Posted by Nam on 8 June 2023 at 5:06 am

    I’m currently wrestling with GA4’s Google Analytics Data API v1 to fetch some json data. It’s a bit quirky though, the response I’m getting back isn’t pure json data. Instead it’s a pair of empty braces {} when I print it using PHP. Funny thing is, with predefined methods we can pick off the values. So I’m scratching my head a bit, wondering if there’s a way to net pure json data straight off the bat. Here’s my PHP gamesmanship, any thoughts?

    (with PHP code)

    Ngoc replied 10 months, 3 weeks ago 3 Members · 2 Replies
  • 2 Replies
  • Matthew

    Member
    10 June 2023 at 9:11 pm

    Absolutely, let me clarify it for you.

    What you’re seeing with your $response object is an instance of GoogleAnalyticsDataV1betaRunReportResponse, which is a kind of protobuf message. This comes from Google’s approach in many APIs where they use protocol buffers for their data format.

    Because of this, you can use a method serializeToJsonString() that’s available for your response object. This method is going to generate a JSON string representation of your object.

    So, just write an echo statement echo $response->serializeToJsonString(); and this will print out your JSON string directly.

  • Ngoc

    Member
    9 July 2023 at 4:12 am

    It seems like the response might be an object that doesn’t directly serialize to JSON. This could be why you’re getting empty braces when you try to print it as such. Although you may not be able to directly convert the response to pure JSON, you could try to iterate through the object and manually build a new one that can be properly serialized. Alternatively, consider delving into the respective PHP methods or using var_dump() to better understand the structure of the response object. This may provide some insight into why the direct conversion isn’t working and what can be done to correct it. Be sure to also check the API documentation for any guidance on how the response should be handled.

Log in to reply.