Array to json using javascript [duplicate] - javascript

This question already has answers here:
JavaScript associative array to JSON
(5 answers)
Closed 4 years ago.
I am trying to pass an array through jQuery's ajax. The problem is that when I try to pass the array created in JavaScript to JSON, it returns something empty. I even try console.log, but when I try to convert it to JSON there is nothing. Here is a representation of how I do it:
var data = [];
data['name'] = 'test';
data['mail'] = 'test';
data['pass'] = 'test';
console.log(JSON.stringify(data)); // result []

Every array is an object. You are assigning object properties with the data['name'] = 'test' syntax. Arrays are indexed with integers and they "must" be in sequence. try a[0] = 'foo'. or Array.push

Related

Why doesn't JavaScript convert a string to an Object? [duplicate]

This question already has answers here:
How to check if object property exists with a variable holding the property name?
(11 answers)
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 5 years ago.
I'm attempting to run a list of strings through an object. When I do it individually it works, but when I pass it through as a string it doesn't work. How would I fix this?
// this doesn't work
var a = "IntegrationItem1";
var data = faq.a;
// but this works
var data = faq.IntegrationItem1;
What's causing the first example to not work? Is the variable data seeing it as faq."IntegrationItem1" instead of faq.IntegrationItem1?
You can access properties of the object using it's names:
var a = "IntegrationItem1";
var data = faq[a];
what you need is faq["IntegrationItem1"] => faq[a]

How to get key values from "array string" in javascript [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Extract values from json string javascript
(3 answers)
Closed 6 years ago.
I have an array in Laravel controller like:
$succeeded[] = array('name' => $name,
'file' => $file
);
...
return $succeeded;
I use an ajax call for getting $succeeded, and I'll have a return string in js function composed of:
"[{"name":"sor.jpg","file":"399393.jpg"}]"
My question is how can I get "name" and "file" values from the string above?
Note: I didn't use any JSON object in controller, but returned just the array. However I wonder it is advantageous to use JSON object.
You first need to parse the response text into a JSON array using the native JSON.parse, and then you can extract the values from the object in the parsed array using dot notation.
var respText = "[{\"name\":\"sor.jpg\",\"file\":\"399393.jpg\"}]";
var arr = JSON.parse(respText)[0]; // Careful - this will throw on invalid JSON
var name = arr.name; // "sor.jpg"
var file = arr.file; // "399393.jpg"

Can you create an associative array in JavaScript? [duplicate]

This question already has an answer here:
JSON Stringify Removing Data From Object
(1 answer)
Closed 6 years ago.
I am trying to set up an associative array in JavaScript and then store it in HTML5 Local Storage:
var student = [];
student["david"] = "He is doing very well";
localStorage['student'] = JSON.stringify(student);
var data = JSON.parse(localStorage['student']);
alert(data.david);
There is no such thing as an "associative array" in JavaScript. You are using a regular array which requires the use of numeric indexes, and adding arbitrary properties to it, which are ignored when you serialize the array to JSON.
The JSON-stringified result will be: "[]".
You need to use a real object:
var student = {}

JSON stringify returns empty string [duplicate]

This question already has answers here:
JSON.stringify doesn't work with normal Javascript array
(6 answers)
Closed 7 years ago.
In Javascript I try to use stringify but it keeps returning an empty string. What is wrong here? Feel free to edit the Fiddle.
JS
values = [];
values['belopp'] = 2322;
values['test'] = 'jkee';
str = JSON.stringify(values);
console.log(values);
console.log(str); // Expected to show a json array
JS Fiddle
https://jsfiddle.net/L4t4vtvd/
You are trying to use something that is meant for an object on an array.
values = {};
values['belopp'] = 2322;
values['test'] = 'jkee';
str = JSON.stringify(values);
This is the updated fiddle.
You are stringifying an array ([]), not an object ({}) Therefore, values = {};

Json object to key value pairs [duplicate]

This question already has answers here:
Fastest way to flatten / un-flatten nested JavaScript objects
(17 answers)
Parse JSON in JavaScript? [duplicate]
(16 answers)
Closed 8 years ago.
I want to convert
var connection = {
someName:'someValue'
}
to
data:{'connection.someName':'someValue'}
how can i do that?
To elaborate more;
I have
var data ={connection : {name : 'SomeName', url:'SomeUrl'}}
and i post
$.ajax({
type : 'POST'
data : data
....
})
and my back-end expects form data like
connection.name='SomeName'
connection.url='SomeUrl'
so it can bind connection data to Connection bean
Thanks.
Whilst the result you are looking for is technically valid JSON, this will not parse as expected:
var x = JSON.parse("{\"data.someName\":\"someValue\"}");
x.data.someName;
// Error: x.data is undefined
This is because the parser treats the entire literal as a single key, so you would have to access the value like so:
var x = JSON.parse("{\"data.someName\":\"someValue\"}");
x["data.someName"]
// "someValue"
What you actually want in order to be compliant, parsable JSON is this:
{"data":{"someName":"someValue"}}
The parser will treat this appropriately:
var x = JSON.parse("{\"data\":{\"someName\":\"someValue\"}}");
x.data.someName;
// "someValue";

Categories