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

using jQuery to eliminate an HTML element based on its attribute

How can I remove an element with the attribute cursor = "pointer"? I want to achieve this using JavaScript in HTML. Specifically, I am looking to remove the following item: <g cursor="pointer"></g>. It's unclear to me why this element has ...

Changing a password on Firebase using Angular 5

I am in the process of developing a settings feature for user accounts on an application I've been working on. One key functionality I want to include is the ability for users to update their password directly from the account settings page. To enable ...

regarding unfamiliar functions in code and their mysterious purposes

My journey learning Vue.js has been going well, but I've hit a roadblock. Can someone explain the meaning of _. in the following code snippet? ...

When using the v-for directive with an array passed as props, an error is

I encountered an issue while passing an array of objects from parent to child and looping over it using v-for. The error message "TypeError: Cannot read property 'title' of undefined" keeps appearing. My parent component is named postsList, whil ...

Error: The variable success_msg has not been defined in the EJS Reference

I am in the process of developing a library website for my school that includes login and administration capabilities. I am relatively new to node.js and EJS, but I recently revamped the routing and page delivery system to use EJS and express. As part of u ...

The debate between client-side and server-side video encoding

My knowledge on this topic is quite limited and my Google search didn't provide any clear answers. While reading through this article, the author mentions: In most video workflows, there is usually a transcoding server or serverless cloud function ...

Tips on extracting the image URL after uploading via Google Picker

I'm currently implementing the Google Drive File Picker on my website for file uploading. Everything seems to be working well, except I am facing an issue with retrieving the image URL for images uploaded through the picker. Below is my current JavaSc ...

What strategies would you use to put in place conditional imports in a way that is reminiscent of ReactNative

Is there a way to implement conditional imports in other projects similar to how React Native imports Android or iOS specific classes using *.android.js and *.ios.js? If I wanted to have different classes for development and production purposes, could I u ...

Retrieving a specific value from a JSON object

I am currently working with a JSON object and I have it displayed in the console. Here is how it looks: [ { "name":"A", "value":"..." }, { "name":"B", "value":"..." }, { "name":"c", "value":"..." ...

Having trouble with my JavaScript code in Visual Studio because of a bundler issue. It's throwing an Uncaught ReferenceError for trying to access a variable before initialization

My AJAX request looks like this: $.ajax({ method: 'GET', url: '/api/some-data', headers: { 'Content-Type': 'application/json' }, success: function(data) { if (data != null) { var userDat ...

Ways to resolve the issue with the Argument of type 'Date[]' not matching the parameter type '(prevState: undefined) in React

I've encountered an issue while trying to construct my project. The error message reads as follows: Argument of type 'Date[]' is not assignable to parameter of type '(prevState: undefined) Here's the excerpt of the code in questio ...

The hovering event trail feature is not functioning in tsParticles, unlike in particlejs

I have two questions regarding the implementation of tsParticles in my React application. First question: <Particles id="tsparticles" options={{ background: { color: { value: "black&quo ...

Yii: Error: The method 'typeahead' is not defined for the object [object Object]

I am currently working on a project using Yii and I encountered a small issue with the Typeahead widget from Yiistrap. It seems that jQuery is being included multiple times - twice before the inclusion of bootstrap.js and once after. Uncaught TypeError: O ...

Updating JSON files from CI variables in Visual Studio Team Services is crucial for maintaining consistency and accuracy

Visual Studio Team Services offers the ability to modify web.config appSetting parameters using values specified in variables. You can find more information on this process here. However, is there a similar method to update a json file? ...

The VueJS Chosen directive fails to refresh when new options are selected

Struggling to populate my jQuery Chosen dropdown field with AJAX data using VueJS. Unfortunately, when trying to update the values, the Chosen dropdown does not reflect the changes. I've experimented with different approaches, including manually trig ...

A conditional stimulus for absence or lack of presence in the input request

The Jolt transformation process should be able to effectively handle scenarios where the request data is null, empty, or absent. Its role is to transform the input data into the desired output as defined in the Jolt specification. These transformations are ...

Enhancing Typography in Material UI with Custom Breakpoints in React CustomThemes

Currently, I am utilizing material UI and React to develop a single-page application (SPA). However, I have encountered an issue with ensuring that my pages are responsive for smaller screen sizes. To address this, I have been manually adding fontSize: { x ...

How to utilize DefinePlugin in Webpack to pass NODE_ENV value

I am attempting to incorporate the NODE_ENV value into my code utilizing webpack through the use of DefinePlugin. I have reviewed a similar inquiry on Stack Overflow, but I am still encountering issues. Here is the configuration I am working with: In pac ...

How can one ensure that Discord waits for a script to complete running, and how can you prevent Discord from responding until all necessary data has been obtained?

I recently started working with node.js and asynchronous programming, and I'm facing a challenge that has me puzzled. My goal is to create a Discord bot that fetches data from a third-party website. While I can successfully retrieve the data and see i ...

Navigating through nested objects in JSON when working with D3: a guide

Currently, I am in the process of learning D3 using various tutorials. Here is the code snippet I have been working with: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title ...