Need to put this object into an array, how? - javascript

I need convert following in the EXACT format shown below with javascript, could you please suggest how to achieve this
from: {"healthy":true,"unhealthy_reasons":[]}
to: [{"healthy":true,"unhealthy_reasons":[]}]

If that's all you need to do, you can just wrap array brackets around the variable that contains the object:
let initialObject = {"healthy":true,"unhealthy_reasons":[]};
let arrayedObject = [initialObject];
But I'm wondering if there's more to this. If this is actually part of a more complicated task, just add that to your question and you'll get a more complete answer.

Use JSON.parse() and JSON.stringify()
let data = '{"healthy":true,"unhealthy_reasons":[]}';
let parsed = JSON.parse(data);
//TO get an array
console.log([parsed])
//TO get a string
console.log(JSON.stringify([parsed]))

Related

How do I parse part of a JSON object that has mixed string and numbers?

I have a JSON file that was processor generated with lines like this
jsonData: "{data: [350.23,250.32,150.34,340.50,236.70,370.45,380.55]}"
I can target the 'jsonData' object but that returns everything within the double quotes as a string.
I tried ...dataset[0].jsonData[8] which returns the '3' from the first value. I guess I could throw the mixed strings into a JS function and use regex to remove the extra stuff, but thats probably the hackyest way to do this.
Whats the easiest way to target the values only?
If you want to interact with it like the list I would consider something like
var list = jsonData.split("[")[1].split("]")[0].split(",")
Console.log(list);
The console reads:
[
'350.23', '250.32',
'150.34', '340.50',
'236.70', '370.45',
'380.55'
]
From here you can use list[3] to get 340.50
If you don't want to spend the time fixing your JSON just do this:
let values = "{data: [350.23,250.32,150.34,340.50,236.70,370.45,380.55]}".split(',').map(_ => _.replace(/[^0-9.]/g,''))
console.log(values)

How to remove double quotes from outside of an Array?

I am taking data from the multiple select that gives me an array data. The data that I am getting is
{provinces: "["1","2"]"}
and when I stringify this data I got
{"provinces":"[\"1\",\"2\"]"}
But what I really want is
{"provinces":["1","2"]}
is there any way ?
use the JSON.parse
var obj = {"provinces":"[\"1\",\"2\"]"}
obj.provinces = JSON.parse(obj.provinces);
console.log(obj)

How to convert a string to JSON format?

I was getting list in array form. So at first place i converted array list to string-
var myJsonString = JSON.stringify(result);
myJsonString="[{"productId":"PI_NAME",
"firstName":null,
"lastName":null,
"customer":null
},
{"productId":"PI_NAME",
"firstName":null,
"lastName":null,
"customer":null
}]"
But again i need to convert myJsonString to Json format, What i need to do? I mean i need to replace 1st" and last ", I guess
You need to call parse now.
JSON.parse(myJsonString)
First, if you ever find yourself building a JSON string by concatenating strings, know that this is probably the wrong approach.
I don't really understand how the first line of your code relates to the second, in that you are not doing anything with JSON-encoded string output from result, but instead just overwriting this on the following line.
So, I am going to limit my answer to show how you could better form JSON from an object/array definition like you have. That might look like this:
// build data structure first
// in this example we are using javascript array and object literal notation.
var objArray = [
{
"productId":"PI_NAME",
"firstName":null,
"lastName":null,
"customer":null
},{
"productId":"PI_NAME",
"firstName":null,
"lastName":null,
"customer":null
}
];
// now that your data structure is built, encoded it to JSON
var JsonString = JSON.stringify(objArray);
Now if you want to work with JSON-encoded data, You just do the opposite:
var newObjArray = JSON.parse(JsonString);
These are really the only two commands you should ever use in javascript when encoding/decoding JSON. You should not try to manually build or modify JSON strings, unless you have a very specific reason to do so.

How to convert this string to some array?

I am using one 3rd party plugin which uses stringify and gives me something like:
["ProjectB","ProjectA","Paris"]
It was an array but it used stringify and serialized into this format.How do I get back my array from this? Now I could very well use split and then remove 1st and last character from every string and get it but I don't want to do that manually. Is that any built in utility that can do that for me?
Assuming you have like var str = '["ProjectB","ProjectA","Paris"]';
Try using,
var array = JSON.parse(str); //will return you an array
As #AlexMA pointed out: JSON.parse is not supported in old browsers so you are better off using jQuery version like below,
var array = $.parseJSON(str);
You can use
JSON.parse(your_arr_str);
or jquery
$.parseJSON(your_arr_str);

How to retrieve value from object in JavaScript

Hi I am using a Java script variable
var parameter = $(this).find('#[id$=hfUrl]').val();
This value return to parameter now
"{'objType':'100','objID':'226','prevVoting':'" // THIS VALUE RETURN BY
$(this).find('[$id=hfurl]').val();
I want to store objType value in new:
var OBJECTTYPE = //WHAT SHOULD I WRITE so OBJECTTYPE contain 400
I am trying
OBJECTTYPE = parameter.objType; // but it's not working...
What should I do?
Try using parameter['objType'].
Just a note: your code snippet doesn't look right, but I guess you just posted it wrong.
Ok, not sure if I am correct but lets see:
You say you are storing {'objType':'100','objID':'226','prevVoting':' as string in a hidden field. The string is not a correct JSON string. It should look like this:
{"objType":100,"objID":226,"prevVoting":""}
You have to use double-quotes for strings inside a JSON object. For more information, see http://json.org/
Now, I think with $(this).find('[$id=hfurl]'); you want to retrieve that value. It looks like you are trying to find an element with ID hfurl,but $id is not a valid HTML attribute. This seems like very wrong jQuery to me. Try this instead:
var parameter = $('#hfurl').val();
parameter will contain a JSON string, so you have to parse it before you can access the values:
parameter = $.parseJSON(parameter);
Then you should be able to access the data with parameter.objType.
Update:
I would not store "broken" JSON in the field. Store the string similar to the one I shoed above and if you want to add values you can do it after parsing like so:
parameter.vote = vote;
parameter.myvote = vote;
It is less error prone.

Categories

Resources