Extract the String data from a JSON file

valeurs_d = "";
                for (var i = 0; i < keys.length -1 ; i++)
                    valeurs_d += + event[keys[i]] + ", ";
                var str5 = ",";
                var str6 = str5.concat(valeurs_d);
                var valeurs = str6.substring (0, str6.length - 2);
                console.log(valeurs);

I am working with a JSON document structured like this:

 {
              "temperature" : 12.45,
              "lala" : 45.75,
              "humidite" : 45.78,
              "toto" : "gvvgvh",
              "topic" : "sk1_001/data"
             }

However, the issue arises when attempting to retrieve the values as I get: 12.45, 45.75, 45.78, NaN!

Is there a way to retrieve my string instead of NaN?

On another note, does typeof in Javascript return number or string? I want to specify varchar for strings and double for numbers.

This is essential for updating my Apache Cassandra database using node.js.

How can I achieve returning varchar and double accurately?

Answer №1

It seems like you are looking to extract all the values from your object. Here is a simple solution for that:

const obj = {
  "temperature": 12.45,
  "lala": 45.75,
  "humidite": 45.78,
  "toto": "gvvgvh",
  "topic": "sk1_001/data"
};

const values = Object.keys(obj).map(key => obj[key]);

console.log(values);

This code will store all the values in an array, but if you prefer a string format, you can use values.join(",").

Answer №2

To concatenate all values within a string using commas as separators, implement the code snippet below

var myObject = {
 "temperature" : 24.32,
 "sample" : 34.56,
 "humidity" : 67.89,
 "test" : "abcde",
 "title" : "sk2_002/info"
 };


var newArray = []; 
for(var key in myObject){
  newArray.push(myObject[key].toString());
}
var finalResult = newArray.join(",");
console.log(finalResult);

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

How to eliminate spaces while preserving line breaks in a textarea using JS or jQuery

I have been trying to figure out how to remove extra spaces from the beginning and end of lines while keeping the line breaks intact. Here's what I attempted: function removeSpaces(string) { return string.split(' ').join(''); } ...

Allowing for the acceptance of null values for strings using rapidjson within cereal by assigning them an empty string ""

I am currently using Cereal, which utilizes RapidJSON, to deserialize JSON into a C++ class. In my case, the issue arises because c++ std::string does not allow for null values. However, other platforms such as .NET and SQL do support null values for strin ...

Revamp your AngularJS controller for a fresh new look

How can a controller be refreshed in Angular? Take into account the scenario below: <div ng-controller="MsgCtrl" ng-repeat="m in messages">{{m}}<br></div> <script> var ws = new WebSocket(something, something); function MsgCtrl($sco ...

What is the reason behind the def.reject code in setTimeout not executing when the sendToSocket operation is successful?

What causes the setTimeout function inside the send method to not run if the sendToSocket operation is successful? this.send = function(type, body) { var def = Promise.defer(); try{ sendToSocket({...}); setTimeout(function() { // ...

Can Next.js 13 support the usage of axios?

Despite trying to implement the SSG operation with the fetch option {cache: 'force-cache'}, I consistently received the same data even when the mock server's data changed. I found that using the fetch option {cache: 'no-store'} do ...

Calculate the total of an array with the help of the angular forEach function

function dialogController(generate, $scope) { $scope.profiles = generate.get_keys('::role'); $scope.content = {}; $scope.options = []; $scope.servers = {}; $scope.subs = {}; $scope.discountList = {}; $sco ...

Having trouble saving user input from a form to a database using axios, mongodb, and vue?

I am a beginner in working with Vue and I'm currently facing an issue while trying to submit user input data to my MongoDB using axios. Although the data from the database is displayed on the page, I can't seem to get the form input data to succe ...

What is the best way to decode a field in Go that has the potential to be either an array or a string?

I am attempting to decode this file: { "@babel/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c5a6aaa1a0e8a3b7a4a8a085f2ebf5ebf5">[email protected]</a>": { "licenses": "MIT", "repository": "https://github.c ...

Creating a Related Entry in strapi v4: A Step-by-Step Guide

Whenever I try to add a new record in my Collection-Type, all the field values are successfully added to the new entry except for the value in the field with a Relation type. For instance, in my event Collection-Type, I have fields like name, performers, ...

Submitting Files to the API using Vue.js

I have the following code in Vue.js and I am trying to upload a file, but my issue is that I want to save the filename of the uploaded file to the JSON API using a POST method. Is there a way to achieve this? Thank you in advance. <div class="input-f ...

Ways to address Path Traversal vulnerability in the following code

const downloadFile = blobstoreRouter.get('/blobstore/download/:filename', (req, res) => { var localFile = path.join(__dirname, '..', escape(req.params.filename)); var file = require('fs').createWriteStream(localFile); try { ...

Validating Angular UI without requiring an input field (validating an expression)

Currently, I am utilizing ui-validate utilities available at https://github.com/angular-ui/ui-validate The issue I am facing involves validating an expression on a form without an input field. To illustrate, consider the following object: $scope.item = ...

Leveraging both onmouseover and onmouseout for container expansion

My goal is to utilize JavaScript along with the HTML events "onmouseover" and "onmouseout" to create a dynamic container. Essentially, I want the container to act as simply a heading when the mouse is not hovering over it, but expand to display additional ...

Combining all elements of my application into a single HTML, JS, and CSS file

My AngularJS app has a specific structure that includes different directories for each component: theprojectroot |- src | |- app | | |- index.html | | |- index.js | | |- userhome | | | |- userhome.html | | | ...

varied reactions between componentDidMount and useEffect when employing jquery emoji plugin

Currently, I am facing an issue with a jquery emoji plugin that I need to use on one of my components until I complete building a custom plugin. Interestingly, when I call the emoji plugin inside componentDidMount, everything works fine, except for the ab ...

Verify the ability to view a webpage

I am currently working on creating a method to check if data access is equal to next.data.access. Since it's an array, I cannot use the includes method. It would be enough for just one of the data access values in the array to return true. auth.guard ...

Is it possible for (variable or {}) to function seamlessly across all web browsers when using Javascript

When writing code in JavaScript, the if(variable) clause is used to check if a list or array is not null or undefined in order to avoid exceptions. Here's an example: if (list) for (var k in list) { ... if (array) for (var i = array.l ...

The datetimepicker is not functioning properly

I'm experiencing an issue with the datetimepicker where it doesn't display a calendar when I click the icon. Interestingly, the Chrome browser isn't showing any errors in the development console. <script src="Scripts/jquery-2.1.1.min.js ...

Encountering a Typescript error while attempting to utilize mongoose functions

An example of a User interface is shown below: import {Document} from "mongoose"; export interface IUser extends Document{ email: string; password: string; strategy: string; userId: string; isValidPassword(password: string): ...

The error message "Data type must be consistent across all series on a single axis in Google Chart" may cause confusion

I'm struggling with an error message that appears when I try to run my Google chart. Here is the code I am using to generate the chart. function (resultVal) { var arrMain = new Array();//[]; for (var i = 0; i < resultVal.length; i++) { ...