0

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.

whb
  • 661
  • 2
  • 10
  • 22
  • Why would you want to have the `data.` in your key? And what is that result, a JSON-like string? – Bergi May 27 '14 at 22:21
  • Actually my back-end expects form data like lets say not data but connection.name='someName', 'connection.url'='someUrl' so it can bind request input to connection bean. Btw i am trying post data with JQuery and on the backend i am using Jodd – whb May 27 '14 at 22:27

1 Answers1

0

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";
Matthew Layton
  • 39,871
  • 52
  • 185
  • 313