I have this string variable built dynamically:
var vData = "[{value: 7, label: '1'},{value: 45, label: '2'},{value: 38, label: '4'},{value: 9, label: '7'}]";
How can I convert my string variable into an array to pass the data parameter?
I've tryed in Javascript with: JSON.parse(vData), but don't work.
In a separated PHP file, I've tryed with: echo json_encode($arr); at the end of PHP file, but don't work.
Where am I wrong?
You'll have to wrap your strings and property names in double quotes for JSON.parse to work. E.g.: [{"value": 7, "label": "1"}]
I'd strongly suggest fixing this in your string generation code, but just to show you it works (definitely not the right regex approach):
var data = "[{value: 7, label: '1'},{value: 45, label: '2'},{value: 38, label: '4'},{value: 9, label: '7'}]";
data = data.replace(/value/g, '"value"');
data = data.replace(/label/g, '"label"');
data = data.replace(/\'/g, '"');
console.log(JSON.parse(data));
Related
Currently I am attempting to parse a long object with JSON.Parse
The object contains a lot of data but specifically this is causing an issue:
OG\'S RIDES
I get this data with an Ajas call.
I convert the data with JSON.stringify
const jsonOrders = JSON.stringify(orders).replace(/[\/\(\)\']/g, "\\$&");
To use this data in an Adobe CEP Panel I pass the data like so:
csiRun.evalScript(`setupSwitchBlade('${jsonOrders}', '${layoutFile}', '${orderDate}', '${productTag}', 1)`);
The object is a large string with multiple items so it would be something like (just an example not valid viewed from console):
{id: 113592, order_number: "204736", internal_order: "204736-0", order_date: "11-15-2021", custom1: "OG\'S RIDES"}
The entire object is being passed as a string and then I have to parse it. I parse it like so:
var orderParsed = JSON.parse(orders);
This causes the error I get JSON.Parse error.
I tracked down the issue to this string also indicated above:
OG\'S RIDES
As you can see the cause of the issue is being escaped but I still get the error.
Any idea how I can solve this?
The error is that JSON format Expecting 'STRING'!
{id: 113592, order_nu
-^
So surround properties with double quotes "
{"id": 113592, "order_number":...}
with a readable format:
const json = `{
"id": 113592,
"order_number": "204736",
"internal_order": "204736-0",
"order_date": "11-15-2021",
"custom1": "OG'S RIDES"
}`
console.log(JSON.parse(json))
//JAVASCRIPT Object:
//{ id: 113592, order_number: "204736", internal_order: "204736-0", order_date: "11-15-2021", custom1: "OG'S RIDES" }
I think the problem is that your properties must be quoted for it to be valid JSON. Don't confuse JavaScript Object Notation (JSON) with JavaScript. :)
input = `{"id": 113592, "order_number": "204736", "internal_order": "204736-0", "order_date": "11-15-2021", "custom1": "OG\'S RIDES"}`
result = JSON.parse(input)
console.dir(result);
The object that you get is not a valid stringified object.
So To fix your issue, you have to stringify the object first and parse it again.
const object = JSON.stringify({id: 113592, order_number: "204736", internal_order: "204736-0", order_date: "11-15-2021", custom1: "OG\'S RIDES"});
// `{"id":113592,"order_number":"204736","internal_order":"204736-0","order_date":"11-15-2021","custom1":"OG'S RIDES"}`
const data = JSON.parse(object);
// {id: 113592, order_number: '204736', internal_order: '204736-0', order_date: '11-15-2021', custom1: "OG'S RIDES"}
I have the following small dataset hardcoded into a variable in my code:
var dataset = [['CENTRAL', 44, 552, 18565],
['NORTHERN', 42, 945, 20092],
['SOUTHERN', 96, 795, 30095],
['PARK', 1, 640, 9341],
['MISSION', 66, 1198, 18542],
['TENDERLOIN', 23, 113, 10735],
['RICHMOND', 9, 561, 9082],
['TARAVAL', 81, 789, 11966],
['INGLESIDE', 5, 1368, 13414],
['BAYVIEW', 7, 985, 14711]];
Now, this dataset is taken directly from a .csv file, that looks like this:
District,Prostitution,VehicleTheft,Totalcrimecount
CENTRAL,44,552,18565
NORTHERN,42,945,20092
SOUTHERN,96,795,30095
PARK,1,640,9341
MISSION,66,1198,18542
TENDERLOIN,23,113,10735
RICHMOND,9,561,9082
TARAVAL,81,789,11966
INGLESIDE,5,1368,13414
BAYVIEW,7,985,14711
However, I'd obviously like to be able to just read in the file, which I've attempted using this:
var dataset_csv = d3.csv("datafile.csv", function(d){
console.log(dataset_csv = d)
});
Which gives me an array of objects that look like this:
[Object, Object, Object, Object, Object, Object, Object, Object, Object, Object]
District: "CENTRAL"
Prostitution: "44"
Totalcrimecount: "18565"
VehicleTheft: "552"
My question is, and it might be trivial, how can I transform those objects into an array data structure like my initial dataset? I've been battling with it for some time now. Any hints greatly appreciated.
Use Array#map to iterate over each object and Object.keys to catch only the keys values.
var dataset_csv = [{District: "CENTRAL", Prostitution: "44", Totalcrimecount: "18565", VehicleTheft: "552"}, {District: "WEST", Prostitution: "22", Totalcrimecount: "4324", VehicleTheft: "53"}, {District: "EAST", Prostitution: "11", Totalcrimecount: "23434" , VehicleTheft: "76"}],
datasetArr = dataset_csv.map(v => Object.keys(v).map(c => Number(v[c]) ? Number(v[c]) : v[c]));
console.log(datasetArr);
I am in process of reverse engineering a JS script. Somewhere is says:
var a = [{
name: 'sample1',
data: ["Otu1", "Otu2", "Otu3", "Otu4", "Otu5"],
values: [5, 15, 250, 20, 23]
},{
name: 'sample2',
data: ["Otu1", "Otu5", "Otu6", "Otu7"],
values: [234, 29, 239, 5]
}]
First question: What type of object is it? is it JSON? Or is it an array of JSON objects?
I need to write this in this form:
var b = {
name: 'sample1',
data: ["Otu1", "Otu2", "Otu3", "Otu4", "Otu5"],
values: [5, 15, 250, 20, 23]
}
var c = {
name: 'sample2',
data: ["Otu1", "Otu5", "Otu6", "Otu7"],
values: [234, 29, 239, 5]
}
var a = b + c
Could you please help? Any insights are appreciated. Thank you community !
"First question: What type of object is it? is it JSON? Or is it an array of JSON objects?"
It's an Array of JavaScript Objects. It could be serialized into JSON data, but currently you should just see it as JavaScript code. The notation is similar, but the resulting data is different.
(And actually in your case, for the notation to be JSON-like, you'd need to use double quotes. But even then, you're still creating JavaScript Objects)
"I need to write this in this form: "
For this, you could make an Array of JavaScript Objects like this:
var a = [b, c];
You have an array of Objects here, remember JSON simply means JavaScript Object Notation
I am reading a value from a dropdown list depending on what option is selected. I am using jqPlot to graph the values.
jqPlot expects an array of values like [91, 6, 2, 57, 29, 40, 95]
but when I read the value in from the dropdown box it is coming in as a whole string "[91, 6, 2, 57, 29, 40, 95]"
I tried splitting it but I got ["91", "6", "2", "57", "29", "40", "95"] which wont display the graph correctly.
Is there anybody that has encountered something like this before and what can I do to make my values convert into a number array.
Thanks for any help
You can use JSON.parse() to convert that string into a JavaScript array. The numbers in the string are not quoted so the array will also contain numbers. And you can delete all the code that parses the string as you won't need it anymore.
>>> JSON.parse("[91, 6, 2, 57, 29, 40, 95]")
[91, 6, 2, 57, 29, 40, 95]
If you need to support legacy browsers, add json2.js to shim JSON support in browsers not supporting it natively.
You can use JSON.parse to change the string "[91, 6, 2, 57, 29, 40, 95]" into an array:
(function(){
var a = '[1,2,3]';
var b = JSON.parse('[1,2,3]');
alert(b +'\n'+ typeof(b)+'\n'+ b[0] );
})()
Demo
As you are using jQuery you can do
$.parseJSON("[91, 6, 2, 57, 29, 40, 95]");
you can use
str.slice(1, -1).split(',').map(function(s){return parseInt(s, 10);});
I'm trying to work with json-framework on iPhone to parse a json string.
When I'm calling this method:
NSDictionary *dictionary = [jsonString JSONValue];
I'm getting the error:
"Error Domain=org.brautaset.JSON.ErrorDomain Code=3 \"Object value expected for key:
Options\" UserInfo=0x4b5f390 {NSUnderlyingError=0x4b5f320 \"Expected value while
parsing array\", NSLocalizedDescription=Object value expected for key: Options}"
According to this json validator [1]: http://www.jsonlint.com// my json is not valid. But is that so??
My json string looks like this:
{
"Options": [
{
"ID": "7",
"A": "1",
"EAt": new Date(2011,
0,
7,
12,
30,
0),
"Type": "Binary",
}
}
* Edited Json: (still brings up an error)
{
"Options": [
{
"ID": "7",
"A": "1",
"EAt": new Date(2011,
0,
7,
12,
30,
0),
"Type": "Binary"
}
]
}
Your JSON is not valid.
It's because you can't create object instances within JSON. It's not a valid value.
new Date(2011, 0, 7, 12, 30, 0)
And you missed the closing array bracket. Everything else is ok.
remove the comma after ...Binary"
add a ] between the two } }.
Date cant be used like this, see How do I format a Microsoft JSON date? and http://msdn.microsoft.com/en-us/library/bb299886.aspx#intro_to_json_sidebarb
This is valid:
{
"Options": [
{
"ID": "7",
"A": "1",
"EAt": "new Date(2011,0,7,12,30,0)",
"Type": "Binary"
}
]
}
You can't instantiate Date objects (or any objects) in a JSON string.
You need to have whoever's responsible for the code that emits this JSON change it to emit valid JSON. They're putting out something now that can't work with any JSON parser. Maybe they have a customized JSON consumer that can handle such things, but this isn't standard JSON.
If I were you, I'd have them put the string of the current date into that field (so: "2011-07-01 12:30:00") and then parse that in your obj-cusing NSDateFormatter.
If whatever puts out that JSON isn't something you can change, you can always modify it locally before feeding it to the JSON library. It's just a string, nothing magical.