Experiencing difficulty with parsing an array's json/string version within an Angular controller

Updated question for clearer understanding!

I'm currently working on an Angular-Rails application and facing challenges when it comes to parsing an array. One of my ActiveRecord models has an attribute that is an array. Before reaching my Angular app, the array appears like this in my Rails controller:

def show
  @thing = Thing.find(params[:id])
# @thing.list => ["{\"content\"=>\"first index\"}", "{\"content\"=>\"second index\"}"]
  render json: @recipe
end

# resulting JSON for @thing:

{
  id: 1,

  title: "thing",

  list: [
          "first index",
          "second index"
        ],
}

Upon entering my angular controller, the array attribute is displayed as:

thing.list => ["{"content"=>"one"}", "{"content"=>"two"}"]

The desired format should be:

[{content: "one"}, {content:"two"}]

I have attempted using JSON.parse on both the Rails and Angular sides of the application, but unfortunately, it did not yield the expected results.

Answer №1

Decoding JSON

If you need to decode a JSON string from an external source or one created within your application, follow these steps:

require 'json'

my_data = JSON.parse('{"greetings": "farewell"}')
puts my_data["greetings"] => "farewell"

Encoding JSON

To create a JSON string for data exchange or serialization, use the following procedure.

require 'json'

my_data = {:greetings => "farewell"}
puts JSON.generate(my_data) => "{\"greetings\":\"farewell\"}"

You can also do it this way:

require 'json'
puts {:greetings => "farewell"}.to_json => "{\"greetings\":\"farewell\"}"

Visit Ruby docs for more information.

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

Tips for positioning a sticky div underneath a stationary header

I'm currently utilizing Bootstrap 4 for my project, and I am encountering an issue with maintaining a div that has the class "sticky-top" just below a fixed navbar. Despite attempting to use JavaScript to replace the CSS while scrolling, it hasn' ...

When attempting to delete, I encounter an error stating that $index is undefined

I am currently working on a project that involves Angular and PHP. I have encountered an issue while trying to delete some information, even though the function seems to be retrieving the data correctly. I'm puzzled as to why it is not working as expe ...

Experimenting with a custom AngularJS filter designed to extract numerical values from a chunk of text

I am working on creating a unique filter that can extract numbers from text input into a text box. For example: User enters: The cat went to 4 stores and bought 3 bags of cat litter for 1 dollar. The desired output would be: [4, 3, 1] This filter works ...

Utilizing RapidAPI in VBA Excel: Discovering Domain Name Ownership

I've come across some other discussions on the same topic, but I haven't been able to find a clear answer. I would really appreciate it if someone could assist me with this problem. I'm trying to integrate RapidAPI into my VBA code in Excel ...

My website using Dynamic Ajax technology is currently experiencing heavy traffic due to the number of getScript

I am facing an issue with my dynamic website where all links fetch new sections via ajax requests from other pages and replace the current section. The problem I encounter has two main aspects. When loading a new div from an Ajax get request, some sections ...

Creating a Discord Bot: Building an Embed Table/List with Segmented Sections

Currently in the process of learning Javascript and venturing into discord.js, I'm fully aware that the code I am working with is not up to par and requires some serious refinements. The main objective here is to split up the arguments of a command a ...

Increase the bottom padding or add some extra space to the Bootstrap form or page

I am currently working on enhancing a Bootstrap Form that includes reset/submit buttons positioned at the bottom. A common issue is when iPhone users attempt to click the Submit button, which initially displays Safari icons before requiring an extra tap to ...

Range slider position not being updated after user interaction

I am working on a webpage with an embedded video and a range slider that serves as a progress bar. Using Javascript, I update the value of the range slider as the video plays, allowing users to navigate through the video content. However, I have encounter ...

The compatibility between Typescript methods and event handlers is lacking

Consider this basic TypeScript script class foo { v: number = 1; public bar() { console.log(this.v); } } var a = new foo(); var b = new foo(); document.getElementById('test').addEventListener("click", a.bar); document.getE ...

Having troubles with delayed state changes due to setState being used within useEffect

I have been working on a slider effect using React Hooks and Redux, and here is the code I am using: const Barchart = ({chartData}) => { let newArray = [] let len = chartData.length const [XArray,setXArray]=useState([chartData]) const [ ...

This error message in AngularJS indicates that the argument 'fn' is not being recognized as a function

I am currently working with angularjs and typescript and I am attempting to create a directive in the following manner: Below is my controller : export const test1 = { template: require('./app.html'), controller($scope, $http) { ...

Launching a Node.js script with pm2 and implementing a delay

Utilizing the amazing pm2 package to maintain the longevity of my node.js applications has been extremely helpful. However, I have encountered a problem that I am unsure how to resolve. One of my applications involves multiple scripts, a server, and sever ...

Encountering a "Module not found" error when trying to integrate NextJs 13.4 with React Query and the

I encountered some issues while working on a NextJs application that utilizes App Router. The problem arose when we decided to switch from traditional fetching to using React Query in server components. To address this, I created a file called api.ts withi ...

Explore by the anchor tag

I've recently implemented a search bar utilizing Bootstrap. This is the code for the search bar: <div class="md-form mt-0"> <input class="form-control" id="myInput" type="text" placeholder="Sear ...

how can you activate a modal without relying on bootstrap?

Could anyone suggest a more efficient way to create a pop-up modal triggered by a button click without relying on bootstrap? I've attempted different methods but haven't achieved the desired result. Here's a sample plunker for reference. Any ...

Creating a javascript function to update content on click

Recently, I've been designing a webpage and encountered an issue. I want the text in a specific area to change whenever a user clicks on a link. Below is the code snippet related to the section I want to modify using a JavaScript function. <div id ...

Changing the contents of a global array in JavaScript

$(document).ready(function(){ var currArray=null; var group=null; var admin=null; var equipment=null; var student=null; console.log("after get array info"); for(var i=0; i<equipment.length; i++) { console.log("equipment at index after get array info ...

Prevent elements from displaying until Masonry has been properly set up

My goal is to merge Masonry elements with existing ones. Currently, the items appear before Masonry initializes then quickly adjust into position a moment later. I want them to remain hidden until they are in their proper place. This is the snippet (with ...

What could be causing the reliability issue with this particular Angular JS code for dropdown menus?

Attempting to create a dynamic country-city dropdown menu using AngularJS <div> Country: </br> <select data-ng-model="country" ng-options="country.name for country in countries" data-ng-change="updateCountry(country) ...

Is there a way to retrieve the HTML code of a DOM element created through JavaScript?

I am currently using java script to generate an svg object within my html document. The code looks something like this: mySvg = document.createElementNS("http://www.w3.org/2000/svg", "svg"); myPath = document.createElementNS("http://www.w3.org/2000/svg", ...