JSON字符串Javascript中的换行符

pwuypxnk  于 2022-11-20  发布在  Java
关注(0)|答案(3)|浏览(166)

我试图从一个JSON文件中读取数据,该文件包含一个博客列表。我想将每个博客拆分成小段落。我以为添加\n可以完成这项工作,但事实并非如此。我该如何实现这一点?

这是我的blogs.json文件:

[
  {
    "id": 1,
    "name": "The 48 Laws Of Power",
    "blog": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. \n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. \n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum",
    "img": "https://i.ibb.co/RpP2LGp/48-Laws-Of-Power.jpg"
  },
  {
    "id": 2,
    "name": "Rich Dad Poor Dad",
    "blog": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. \n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. \n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum",
    "img": "https://i.ibb.co/8Brh2Nc/rich-Dad-Poor-Dad.jpg"
  },
  {
    "id": 3,
    "name": "Show Your Work",
    "blog": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. \n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. \n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum",
    "img": "https://i.ibb.co/VjLBT1T/show-Your-Work.jpg"
  },
  {
    "id": 4,
    "name": "Atomic Habits",
    "blog": "Atomic Habits by James Clear is an incredible book on habits and the massive effect that they have on our lives. Published in 2018 and now an international bestseller, Atomic Habits centers around this idea that “habits are the compound interest self-improvement.” If you want to improve yourself in any way, look first to your daily habits. \n Clear relates habits to compound interest; an interesting model he suggests that really helped me visualize the effect that these tiny behaviors had on our lives is set up like this. \n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. \n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. \n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum",
    "img": "https://i.ibb.co/ss0kLQw/atomic-Habits.jpg"
  },
  {
    "id": 5,
    "name": "The Almanack Of Naval Ravikant",
    "blog": "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. \n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum. \n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum",
    "img": "https://i.ibb.co/87SmcFz/alamanack-naval.jpg"
  },
  {
    "id": 6,
    "name": "The 4-Hour Work Week",
    "blog": "The first chapter, D is for Definition, followed its name and defined the clear cut differences in mindset between the new rich and the deferrers. This clued me in to the goal of this book, to escape what has been perpetuated our entire lives. However, I was still skeptical. It presented several, grandiose claims; how could any of it be truly doable? Sure, someone like Tim Ferriss, Princeton graduate and energy-supplement extraordinaire could pull it off, but that doesn't mean that me, the average Joe, could somehow make an automated stream of revenue so that I can live all around the world and have no worries.The next chapter, E is for Elimination, had the most profound effect on me. It presented ideas such as Parkinson's Law (work expands to fill the time allotted to it) and the Pareto Principle (80/20), ideas I had heard from videos before, but never explained as well as in this chapter. After reading, I immediately evaluated my time wasters and consumers and began to slowly deconstruct my day and how to best optimize it. This chapter was one that I could apply the day after reading it successfully, so it was very useful. \n The next chapter, E is for Elimination, had the most profound effect on me. It presented ideas such as Parkinson's Law (work expands to fill the time allotted to it) and the Pareto Principle (80/20), ideas I had heard from videos before, but never explained as well as in this chapter. After reading, I immediately evaluated my time wasters and consumers and began to slowly deconstruct my day and how to best optimize it. This chapter was one that I could apply the day after reading it successfully, so it was very useful. \n Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum",
    "img": "https://i.ibb.co/Pxtt4dH/4-hour-work-week.jpg"
  }
]

我是这样阅读的

import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";

const BookDetails = () => {
  const { id } = useParams();
  const [blog, setBlog] = useState({});

  useEffect(() => {
    const url = `/blogs.json`;
    console.log(url);
    fetch(url)
      .then((res) => res.json())
      .then((data) => {
        const currentBlogArray = data.filter((book) => book.id == id);
        setBlog(currentBlogArray.length > 0 ? currentBlogArray[0] : {});
      });
  }, []);

  return (
    <div className="px-6">
      <h2>This is book details: {id} </h2>

      <h2 className="flex justify-center font-bold text-2xl mb-6">
        {" "}
        {blog.name}
      </h2>
      <h2> {blog.blog}</h2>
    </div>
  );
};

export default BookDetails;
rfbsl7qr

rfbsl7qr1#

您可以为字符串上的每个所需位置添加<p>标记,然后在阅读JSON时根据<p>标记将其拆分,然后创建您自己的HTML。
例如:
第一个

import React, { useEffect, useState } from "react";
import { useParams } from "react-router-dom";

const BookDetails = () => {
  const { id } = useParams();
  const [blog, setBlog] = useState({});
  useEffect(() => {
    const url = `blogs.json`;
    fetch(url)
      .then((res) => res.json())
      .then((data) => {
        const currentBlogArray = data.filter((book) => book.id == id);
        const currentBlog =
          currentBlogArray.length > 0 ? currentBlogArray[0] : {};
        setBlog({
          ...currentBlog,
          blog: currentBlog.blog.split("\n"),
        });
      });
  }, []);

  return (
    <div className="px-6">
      <h2>This is book details: {id} </h2>
      <h2 className="flex justify-center font-bold text-2xl mb-6">
        {blog.name}
      </h2>
      <h2>
        {blog.blog?.map((paragraph) => {
          return (
            <p>
              <span style={{ marginLeft: 25 }}></span>
              {paragraph}
            </p>
          );
        })}
      </h2>
    </div>
  );
};

export default BookDetails;
2lpgd968

2lpgd9682#

替换 :

<h2> {blog.blog} </h2>

中 的 每 一 个

<h2> {blog.blog.split(/\n/).map((t,i) => (<div key={i}>{t}</div>))} </h2>

格式
这 将 在 换行符 处 拆分 文本 ( 丢弃 它 ) 。 每个 结果 子 字符 串 随后 被 Map 到 div 以 供 显示 。

chy5wohz

chy5wohz3#

\\n\\替换为\n可添加一个换行符。使用\n\n可添加两个换行符。

相关问题