-1

I have field description which contains a JSON object and I want to parse it.

When I console.log(description) it displays the object content and also displays the object on the page.

{"blocks":[{"key":"1i9ik","text":"Issue Title","type":"header-three","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}},{"key":"4nluf","text":"Hi,","type":"unstyled","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}},{"key":"evi0t","text":"","type":"unstyled","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}},{"key":"5s8vp","text":"Lorem Ipsum is simply dummy text of the printing and typesetting industry.","type":"unstyled","depth":0,"inlineStyleRanges":[{"offset":0,"length":11,"style":"BOLD"}],"entityRanges":[],"data":{}},{"key":"fkbca","text":"Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, ","type":"unstyled","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}},{"key":"3dc6a","text":"when an unknown printer took a galley of type and scrambled it to make a type specimen book.","type":"unstyled","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}},{"key":"8rfom","text":"","type":"unstyled","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}},{"key":"es2ha","text":"one","type":"ordered-list-item","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}},{"key":"aeon1","text":"Two","type":"ordered-list-item","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}},{"key":"ei5sb","text":"Three","type":"ordered-list-item","depth":0,"inlineStyleRanges":[],"entityRanges":[],"data":{}},{"key":"bo9vp","text":"Urgent","type":"unstyled","depth":0,"inlineStyleRanges":[{"offset":0,"length":6,"style":"BOLD"},{"offset":0,"length":6,"style":"UNDERLINE"}],"entityRanges":[],"data":{}}],"entityMap":{}}

But I want to parse this object using the JSON.parse() method and when I console.log the parsed object or try to display the parsed object it gives the following error.

Uncaught SyntaxError: Unexpected token u in JSON at position 0

code:-

import { useEffect, useState } from "react";
import { useNavigate, useParams } from "react-router-dom";
import { useSelector, useDispatch } from "react-redux";

import { Editor, EditorState, convertFromRaw } from "draft-js";

const PostPage = () => {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const { postId } = useParams();

  const [description, setDescription] = useState();

  const { post, isSuccess } = useSelector((state) => state.posts);

  useEffect(() => {
    dispatch(getpost(postId));
  }, [dispatch, post]);
   
  console.log(post.description);


  const contentState = convertFromRaw(post?.description);
  const editorState = EditorState.createWithContent(contentState);

  return (
    <>
      <div className="wrapper">
        <div className="post-details-container">
          <div className="post-details">
            <div className="post-header">
              <div className="post-header-subject-created-at">
                <div className="post-header-subject">{post.subject}</div>
              </div>
            </div>
            <div className="post-content-container">
              <div className="post-content-header-container">
                <div className="post-content-header">
                  <div className="post-content-username">
                    <div className="post-username">{post.name}</div>
                  </div>
                </div>
              </div>
              <div className="post-content-description">
                <Editor editorState={editorState} readOnly={true} />
              </div>
            </div>
          </div>
        </div>
      </div>
    </>
  );
};

export default PostPage;

What am I doing wrong?

  • 2
    The JSON might already be parsed? It looks like an object already. Please may you add a [mcve]? – evolutionxbox Apr 27 '22 at 15:46
  • post your full code – Sean Apr 27 '22 at 15:47
  • it's already a json. you don't have to parse it – R4ncid Apr 27 '22 at 15:47
  • 1
    @R4ncid that would mean it's not JSON. (JSON is the string _before_ it's parsed) – evolutionxbox Apr 27 '22 at 15:48
  • What you're showing is not JSON, it's simply an object. You don't need to "parse" an object. Can you clarify what exactly you're trying to do? – David Apr 27 '22 at 15:49
  • 1
    @evolutionxbox you are right! I mean object :) – R4ncid Apr 27 '22 at 15:50
  • Regarding the update... You are logging `description` to the console, but trying to parse `post.description`. How are those related? At runtime, what *is* `post.description`? Is it JSON? The error pretty strongly implies that it isn't. – David Apr 27 '22 at 15:51
  • @David If I directly use the description in the draft js editor component then it gives an error "uncaught TypeError: Cannot read properties of undefined (reading 'blocks')" –  Apr 27 '22 at 15:53
  • @David edited it should be ```post.description``` –  Apr 27 '22 at 15:55
  • 1
    @TejasP: And how is that related to the question being asked here? It's clear that there are problems to be solved in the code in general, but let's focus on one error at a time. Currently, in the code shown you're trying to parse a value as JSON. The error suggests that the value is not JSON at all. Do you have information indicating otherwise? So far it sounds like the answer is simply, "You don't have to JSON-parse values which aren't JSON." – David Apr 27 '22 at 15:56
  • @David ok it is already parsed now when I pass it to the editor component as given in the draft js example it gives error ```uncaught TypeError: Cannot read properties of undefined (reading 'blocks') ``` –  Apr 27 '22 at 16:00
  • @TejasP: When you debug, what is the exact runtime value of `editorState` being passed to that component when the error occurs? What is the exact runtime value of `post` which produces it? You keep making changes to the code shown, so we really have no idea what's the actual code you're using and what you're just changing in the question itself without testing/debugging those changes. (The question which, in its current state, asks about `JSON.parse` but doesn't use it anywhere.) If I were to **guess**, it sounds like `post` may be getting modified asynchronously. – David Apr 27 '22 at 16:04
  • @David I checked the type of(post.description) it is showing string for me. –  Apr 27 '22 at 16:04
  • @TejasP: That's great, but not all strings are JSON. For example, `JSON.parse("Not all strings are JSON.");` will produce the same error noted in the question, and for the same reason. Did you happen to check what **value** that string has? Is that value *actually JSON*? If you're trying to parse a string into another data type and that parsing fails, step 1 of your debugging is to observe what that string actually is. – David Apr 27 '22 at 16:09
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/244260/discussion-between-tejas-p-and-david). –  Apr 27 '22 at 16:12
  • @TejasP: Let's not. Now would probably be a good time for you to delete this question and re-visit the issue with a new [mcve] which demonstrates the problem. In a new question, indicate specific debugging observations and exactly which operation is failing unexpectedly. The question asked above has undergone too many drastic changes, and the comment thread tries to ask about an unrelated problem. This is unsalvageable. For tips and information on asking a question, please see [ask] and its linked resources. – David Apr 27 '22 at 16:14

1 Answers1

1

Actually it's already an Object. No need to implement JSON.parse, just use the object to access directly.

Following is an example:-

enter image description here

Ali Abbas
  • 540
  • 4
  • 10
  • [link](https://freeimage.host/i/typeof.Vsp1kP) for me type is showing as a string. –  Apr 27 '22 at 16:07