Data Structures & Algorithms

JSON Multi-Line String

“JSON is a popular data-interchange format that has been widely adopted across the development community. However, JSON has strict schema and formatting tools.

JSON does not natively support multi-line strings. This can be quite frustrating when looking for flexibility and storing large texts.

Let us discuss a simple workaround and how we can use multiline strings.”

Using a JSON Array

A creative way of inserting a multi-line string in JSON is to use an array. We can separate each line as an individual element of the array.

For example, let us say we have a sample text as shown:

Lorem ipsum dolor sit amet. Aut eveniet sequi sit sequi dicta vel impedit architecto 33 voluptas tempore et optio libero qui molestiae possimus. Aut cupiditate animi ut commodi natus ut nesciunt mollitia ea ipsam iusto a ipsa odit a laboriosam neque et vero totam.

If we want to convert the above block of text into JSON, we can convert each line into an array element.

For example:

    [
        "Lorem ipsum dolor sit amet.",
        "Aut eveniet sequi sit sequi dicta vel impedit architecto,",
        "33 voluptas tempore et optio libero qui molestiae possimus.",
        "Aut cupiditate animi ut commodi natus ut nesciunt mollitia ea,",
        "ipsam iusto a ipsa odit a laboriosam neque et vero totam."
    ]

Note how each line of the above string is converted into an array element separated by a comma.

You can then use a method in your preferred programming language to construct the string back to its individual block.

Conclusion

This tutorial provides a simple but creative way of creating a multi-line string in JSON.

About the author

John Otieno

My name is John and am a fellow geek like you. I am passionate about all things computers from Hardware, Operating systems to Programming. My dream is to share my knowledge with the world and help out fellow geeks. Follow my content by subscribing to LinuxHint mailing list