Reputation: 14275
I have a string like this:
string = '{ "key": [
{ "foo": "bar" }
] }';
This string is converted into a JSON object by doing
json = $.parseJSON(string);
and then it looks like this:
{ "key":
{ "0":
{ "foo": "bar" }
}
}
So it seems like the array was converted into a hash.
The desired outcome would instead be:
{ "key": [
{ "foo": "bar" }
] }
What's the best way to achieve this? Background: I am posting JSON data to a URL but need the array to stay intact so the recipient can parse it accordingly.
Update
Here is what I see in a console of Chrome 37.0.2062.120 and jQuery 1.11.1:
It looks like an array, but is really just another hash with a key of "0". Or am I getting something wrong?
Update 2
After converting the string into a JSON update I am posting it to a url:
$.ajax({
url: 'http://test.com',
data: json,
dataType: 'jsonp',
type: 'post'
})
where it arrives as
{ "key":
{ "0":
{ "foo": "bar" }
}
}
Upvotes: 2
Views: 2560
Reputation: 92274
When you send the AJAX, you can encode the JSON yourself
For JSONP, use
var json = '{ "key": [ { "foo": "bar" }] }';
var jsObj = $.parseJSON(json);
$.ajax({
url: 'http://test.com',
// You have to convert your JS object into a JSON string on your own
// jQuery will convert them into form encoded values if you leave it as an object
// But you want to send your whole JSON as one of the keys,
// so do use an object around your json to specify the the name of the
// key value pair containing the JSON
data: {myKey: JSON.stringify(jsObj)},
dataType: 'jsonp',
// The answer at http://stackoverflow.com/questions/6410810/rails-not-decoding-json-from-jquery-correctly-array-becoming-a-hash-with-intege
// suggests you may need this for Rails to understand it
contentType: 'application/json'
// type can't be post for JSONP
// type: 'post'
})
For a POST, use
$.ajax({
url: '/my/url/',
// For POST, you can post the entire string, converting it on your own
data: JSON.stringify(jsObj),
type: 'POST'
})
Upvotes: 2
Reputation: 2837
In Javascript, everything is a hash of key and value which is why you see hash for Arrays with index as hash key and value as object.
This works for me.
var jsonStr = '{ "key": [{ "foo": "bar" }] }';
var obj = $.parseJSON(jsonStr);
if (obj.key instanceof Array) {
alert('value is Array! and its length is > '+obj.key.length);
} else {
alert('Not an array');
}
Upvotes: 1
Reputation: 181
On the one hand, that all needs to be wrapped up in braces like so
string = '{"key": [
{ "foo": "bar" }
]}';
Which is going to let jQuery parse it with jQuery.parseJSON(string)
It's wrapped up in an array, which is why you're getting an array. I'm guessing here, but is what you really want:
string = '{"key":
{ "foo": "bar" }
}';
so that you can access "bar" by just hitting array['key']['foo']
? If so, remove those brackets.
Upvotes: 0