Reading JSON documents in JavaScript through multiline strings

Having a JSON document with multiline string data is causing issues for me.

I have attempted multiple options, but none of them have successfully solved the problem.

For example:

[
  {
    "someString" : "A rather long string of English text, an error message \
               actually that just keeps going and going -- an error \
               message to make the Energizer bunny blush (right through \
               those Schwarzenegger shades)! Where was I? Oh yes, \
               you've got an error and all the extraneous whitespace is \
               just gravy.  Have a nice day."
  }
]

or

[
  {
    "someString" : `A rather long string of English text, an error message` +
               `actually that just keeps going and going -- an error` +
               `message to make the Energizer bunny blush (right through` +
               `those Schwarzenegger shades)! Where was I? Oh yes,` +
               `you've got an error and all the extraneous whitespace is` +
               `just gravy.  Have a nice day.`
  }
]

or

[
  {
    "someString" : 'A rather long string of English text, an error message' +
               'actually that just keeps going and going -- an error' +
               'message to make the Energizer bunny blush (right through' +
               'those Schwarzenegger shades)! Where was I? Oh yes,' +
               'you've got an error and all the extraneous whitespace is' +
               'just gravy.  Have a nice day.'
  }
]

or using \n as suggested in the comments, which also did not work.

[
  {
"shortStory": "A rather long string of English text, an error message\n
           actually that just keeps going and going -- an error \n
           message to make the Energizer bunny blush (right through\n
           those Schwarzenegger shades)! Where was I? Oh yes,\n
           you've got an error and all the extraneous whitespace is\n
           just gravy.  Have a nice day."
  }
]

Despite trying various other combinations, any newline characters seem to disrupt the code functionality.

Below is the Angular 2/Javascript code that reads the JSON file:

   import {
        Injectable
    } from '@angular/core';
    import {
        Http,
        Headers,
        RequestOptions,
        Response
    } from '@angular/http';
    import {
        Observable,
        Subject
    } from 'rxjs/Rx';
    import 'rxjs/Rx'; //get everything from Rx
    import 'rxjs/add/operator/toPromise';
    import {
        IArticle
    } from './article';

    @Injectable()
    export class ArticleService {
        private jsonFileURL: string = "./assets/data/article-data.json";
        constructor(private http: Http) {}
        //
        getArticles(): Observable < IArticle[] > {
            return this.http.get(this.jsonFileURL).map((response: Response) => {
                return <IArticle[] > response.json()
            }).catch(this.handleError);
        }
        //
        private handleError(errorResponse: Response) {
            //console.log(errorResponse.statusText);
            return Observable.throw(errorResponse.json().error || "Server error");
        }
    }

Answer №1

Per @Patrick's suggestion, I have replaced the newline literals with \n in the JSON data for better readability.

[{"shortStory": "The free bird leaps\n on the back of the wind\nand floats downstream\ntill the current ends\nand dips his wings\nin the orange sun rays\nand dares to claim the sky.\n\nBut a bird that stalks\ndown his narrow cage\ncan seldom see through\nhis bars of rage\nhis wings are clipped and\nhis feet are tied\nso he opens his throat to sing.\n\nThe caged bird sings\nwith fearful trill\nof the things unknown\nbut longed for still\nand his tune is heard\non the distant hill\nfor the caged bird\nsings of freedom\n\n The free bird thinks of another breeze\n and the trade winds soft through the sighing trees\n and the fat worms waiting on a dawn-bright lawn\n\n and he names the sky his own.\n\n But a caged bird stands on the grave of dreams\n his shadow shouts on a nightmare scream\n his wings are clipped and his feet are tied\nso he opens his throat to sing\n\nThe caged bird sings\n with a fearful trill\n of things unknown\n but longed for still\n and his tune is heard\n on the distant hill\n for the caged bird \n sings of freedom"}]

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 could be the reason for a missing button in the Bootstrap navbar on smaller devices?

I'm new to Bootstrap and noticed on smaller devices, there is no visible button to tap for displaying the menu items. However, tapping on the upper right-hand side does reveal them. What could I be missing here? index.html <!DOCTYPE html& ...

Interactive Image Component in React

I'm encountering an issue with my React code. import { useState, useEffect } from "react"; import { useParams } from "react-router-dom"; import RecipeService from "./RecipeService"; import RecipeProfileImg from "./Re ...

How can cookies be managed with JavaScript, Express.js, or Node.js?

Could anyone advise on the optimal approach for managing cookies - through Express.js, Node.js, or client-side JavaScript/jQuery? I'm feeling a bit uncertain about security implications. Your assistance and insights are greatly appreciated. ...

The continuous resizing of the window is triggering a loop in flexslider when the resize function is called

I am currently working on a website that utilizes the flexslider plugin. My goal is to detect when the browser window is resized, and then reinitialize the slider so that it can adjust its size and other parameters accordingly. Initially, I was able to a ...

Modify the parent div's background color on mouseover of the child li

I want to update the background image of a parent div that contains a series of ul li elements. Here is the HTML code I am working with: <section class="list" id="services"> <div class="row"> <ul> <li>& ...

Ways to customize the selected item's color in md-select using Angular Material?

Currently, I am utilizing the dark theme in angular-material 1.0.4. The appearance of the select element is different when an item is selected: Comparatively, this is how it appears with the default theme applied: The dark theme fails to handle color eff ...

Traverse JSON data using associative loops

Is there a way for me to iterate through this JSON data without using numerical indexes? I want to treat it like an associative array. This is what I have so far: $.post('/controlpanel/search', { type: type, string: string }, function(data){ ...

What is the best way to utilize date-fns for formatting a date retrieved from an API?

After receiving data from an API in the 'yyyy-MM-dd' format, I encountered a display issue when trying to convert it to 'dd-MM-yyyy'. How can I properly adjust the date format without disrupting the table display? onMounted(async () =& ...

Showing additional content in an alternative design

I'm currently facing an issue with the "load more" post button on my Wordpress site. I've designed a unique grid layout for the category page, with a load more button at the bottom. However, when I click the button to load more posts, they appear ...

Transform data from ceilometer into a pandas dataframe using Python

As a newcomer to Python and openstack ceilometer, I am currently working on reading ceilometer data. The code snippet below shows how I am achieving this: import ceilometerclient.client cclient = ceilometerclient.client.get_client(2, os_username="Ceilome ...

Refresh the module.exports in a Mocha unit testing script

I am currently learning about nodejs and mocha, and I have developed a JavaScript program to display the files in a folder along with a unit test case using the mocha and chai framework. My goal here is to reset the object set in module.export before each ...

Reactjs, encountering a hitch in utilizing material UI: Incompatible hook call detected

As a newcomer to React, I decided to incorporate Material UI components into my project. After installing the components locally using npm install and importing them into my project, I encountered an error when trying to run start: Error: Invalid hook call ...

Tips for arranging buttons horizontally in Angular

After adding a third button, I noticed that the buttons were now displaying in a column instead of a row. html: <div class="creator-button-container" *ngIf="isCurrentUserTheChannelCreator"> <div *ngIf="isChannelE ...

The custom classes I have created in Material UI are being overshadowed by the default classes provided by Material UI

I am trying to change the color of a TextField label to black when it is focused. I used classes in InputProps with a variable, but unfortunately, the default styling of material UI is taking precedence in chrome dev tools. Below is the code snippet. Pleas ...

What is the method for condensing content using a Bootstrap toggle button (checkbox)?

Incorporating Bootstrap 5.1, I have a set of buttons that trigger the display or hide some content using the collapse plugin <div class="col m-2"> <button type="btn" class="btn btn-outline-primary m-1" d ...

Tracking Command Cooldowns in Discord.js: How to Calculate Time Remaining

Is it possible to modify the cooldown feature so that it shows the remaining time until the user can work again, rather than displaying a fixed wait time message? const { RichEmbed } = require("discord.js"); const { stripIndents } = require("common-tag ...

Issues with retrieving JSON data from Google Books API object

I've been working on retrieving data from the Google Books API and displaying the titles of the first 10 results on a web page. The site is successfully making the request, and I have a callback function that handles the results as shown below: funct ...

Guide on modifying cube material dynamically in WebGL at runtime

Currently, I am utilizing three.js to create animations. My goal is to dynamically modify the material of a cube mesh. Below is an example: // Create cube geometry var material1 = [new THREE.MeshBasicMaterial({color:0xBEE2FF}),.....]; var geometry = new ...

Automated Copy and Paste Feature - JavaScript using Ajax

I am working on a unique auto-increment IMDB ID grabber that retrieves the ID as you type the name of a TV show. Currently, I have managed to create functionality where it checks if the field is empty; if not, it displays a button that directs you to a pag ...

Error: The javascript function is unable to execute because undefined is not recognized as a function

I've been struggling with an error in my "bubble sort" function that I wrote to organize a list of images. Whenever I run the function, I keep getting the message "Uncaught TypeError: undefined is not a function". Can anyone provide some guidance? $j ...