Extracting data from the Sanity API response in JSON format using Typescript

Struggling with extracting information from a Sanity Client API call and decoding the resulting JSON data. Can someone guide me on how to access specific values?

Below is the output of the API call:

[
  {
    slug: { current: "test-post", _type: "slug" },
    authors: [
      {
        last_name: "xxx",
        profile_picture: "/images/xxx.png",
        _key: "xx",
        first_name: "xx",
        email: "xxx",
        _type: "author",
        bio: "xxxx  ",
      },
    ],
    // Other key-value pairs
    title: "This is the title of the post2"",
    _createdAt: "2023-01-21T23:38:11Z"
  },
];

The provided code snippet shows my attempt to process the retrieved data.

const result = await SanityClient.fetch(`*[_type == "post"] | order(publish_date desc)`,);
        const document = JSON.stringify(result);
        const post:Post = {
            title: document['title'],
            slug: document['slug.current'],
            headline: document[1]['headline'],
            publish_date: document['publish_date'],
            banner_image: document['banner_image'],
            category: document['category'],
            author: document['author'],
            body: document['body']
        }

I'm struggling to understand how to navigate through the properties in the 'document' object. Specifically, unsure about accessing the 'headline' attribute.

Your expertise on this matter would be greatly appreciated!

Answer №1

After some trial and error, I finally cracked the code.

I realized that my use of the Stringify function was altering the output format from Sanity. So, I decided to eliminate the line

const document = JSON.stringify(result);

Instead, I started referencing the attribute through result[0]['title'] in order to retrieve the title...

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What steps should I follow to configure tastypie to support a JSONField?

Currently, I am encountering an issue where I receive a "BAD REQUEST: '' is not a valid JSON string." error message when attempting to post data to my tastypie API. The API I am working with contains a ModelResource that is linked to a model feat ...

What is the best way to store article IDs using Javascript or HTML?

On my web page, I have a collection of links that users can interact with by clicking and leaving comments. These links are loaded through JSON, each with its unique identifier. But here's my dilemma - how can I determine which link has been clicked? ...

Do null and undefined fall under other types as subcategories in Typescript?

As I was exploring some old code, I came across the following snippet: let isNew: boolean = null let myName: string = undefined This snippet seems to indicate that in typescript, a variable of type boolean can accept null and a variable of type string can ...

Tips on sending multiple files using RMongo

Following the guidelines found at http://docs.mongodb.org/manual/reference/method/db.collection.insert/ I am looking to upload a batch of multiple documents in a single RMongo::dbInsertDocument call. data = data.frame(A=c(1,2), B=c(3,4)) L = lapply(s ...

What is the method for retrieving the ObjectMapper utilized by the JacksonProvider in RestEasy for parsing a .json file?

Within my RestEasy application that utilizes Spring, I have made enhancements to the ObjectMapper configuration by extending RestEasyJacksonProvider. The code snippet below showcases how the customization has been implemented: public class JacksonProv ...

What is the process for combining an object and a primitive type to create a union type?

Having a tricky time with Typescript and finding the correct typing for my variable. What seems to be the issue? The variable selected in my code can either be of type DistanceSplit or number. I have an array that looks like this: [-100, DistanceSplit, D ...

Utilizing custom hooks for passing props in React Typescript

I have created a unique useToggler custom hook, and I am attempting to pass toggle props from it to the button child in the Header component. However, when I try using toggle={toggle}, I encounter this error: Type '{toggle: () => void;}' is ...

Tips for correctly displaying diacritics with Webpack and Typescript

While working on my project, I encountered an issue with diacritics marks (such as German or Polish characters) when using Webpack with Typescript. Unfortunately, the problem arises when trying to display these marks in the console or on a webpage. It seem ...

Sending data to a child component in Angular 2 just one time

In my current project, I'm working with 2 components: detail (parent) and update (child). My goal is to have the update component's initial values, set as a form, based on an object that the detail component possesses. To achieve this, I am util ...

Troubleshooting Angular 2 Karma Error: Module Parse Failed due to missing loader for file type

I'm currently configuring Karma for my Angular 2 application and I seem to be facing an issue with a missing plugin. Could anyone provide assistance with this matter? I am utilizing the following repository as a reference: https://github.com/AngularC ...

Encountering the error message `TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts"` with `ts-node` when the type is specified as module

After configuring absolute paths in my Express project and changing the type to module for using import, I encountered an error: TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" Below is the content of my tsconfig.json { &q ...

Incorporating the root element into API blueprint with the utilization of data structures

I've spent hours trying to make this work, pouring over all the documentation. How can I ensure that my array follows the JSON specification by having a root element, using the data structures I've already defined? What adjustments do I need to ...

Errors have been found in the validation process and need to be

When working with Grails 2.3, I am facing an issue where I need to send a customized error message in JSON format. However, when I utilize the following code snippet: class ApiError { String message String status Exception error } and try to ...

I'm struggling with finding an answer to this question: "What is the most effective way to conduct a

I'm experimenting with a file upload. I decided to encapsulate the FileReader() inside an observable based on information I found in this discussion thread: onFileSelected(event: any) { this.importJsonFileToString(event.target.files[0]) .p ...

Recursive rendering of tree components in React

I am facing a challenge in rendering tree items recursively using React. I have been struggling to achieve the desired outcome as calling treeRender(children) seems to alter the data structure when a folder is encountered for the first time. I am curious a ...

Guide on writing directly to a JSON object using ObjectMapper in Jackson JSON

I am attempting to output to a JSON object using Jackson JSON, but I am encountering issues with the current code. public class MyClass { private ObjectNode jsonObj; public ObjectNode getJson() { ObjectMapper mapper = new O ...

Encountering limitations in accessing certain object properties with the openweathermap API

As I integrate axios into my react application to retrieve weather data from the openweathermap api, I'm encountering some issues with accessing specific properties from the JSON object returned by the API call. For instance, I can easily access data. ...

Is there a way to transform a string containing dot notation and arrays into JSON?

I need assistance with converting a string in dot notation to JSON format. Consider the following key-value pairs in a Dictionary<string, object>: key: "resource.person[0].name" value: "bob" key: "resource.person[1].name" value: "dylan" The co ...

Issue: Unhandled promise rejection: BraintreeError: The 'authorization' parameter is mandatory for creating a client

I'm currently working on integrating Braintree using Angular with asp.net core. However, I've encountered an issue that I can't seem to solve. I'm following this article. The version of Angular I'm using is 14, and I have replicate ...

The background image is not being properly applied by React's makeStyles

Even after attempting various methods to load the image for the backgroundImage property, it still does not appear on the page. Interestingly, loading external images (such as those from Google) works just fine. I experimented with the following: backgro ...