JSON dot notation to string

2019-03-04 15:55发布

问题:

I am using JSON within my javascript and I am trying to get a string value for the dot notation representation.

For example AAA.BBB[0].CCC.DDD[5].EEE = 123 in JSON dot notation format.

But I want to get the value AAA.BBB[0].CCC.DDD[5].EEE as a String so I can save it for later use to allow me to modify my JSON code directly.

Is there a method in Javascript or jQuery that can return a string value representation?

*EDIT I am converting JSON data into a list structure, and I want to save the AAA.BBB[0].CCC.DDD[5].EEE format as the id so when a user modifies the content of that list item it modifies the JSON data directly. Would there be a better way to save the location in the id?

回答1:

Why not just store a reference to an inner-portion of it? Storing it as a string doesn't make much sense. If you just want a shorter way of accessing it, storing a reference makes more sense.

var theCollection = AAA.BBB[0].CCC.DDD[5];
alert( theCollection.EEE );

this reference can then be stored on an element and retrieved later.

$(someelement).data("jsonref",theCollection);
var data = $(someelement).data("jsonref");
alert(data.EEE);
data.EEE = "foobar";
data = $(someelement).data("jsonref");
alert( data.EEE );


回答2:

var j_string = JSON.stringify(AAA.BBB[0].CCC.DDD[5].EEE);

If you just want the value returned as a string do this:

var j_string_value = AAA.BBB[0].CCC.DDD[5].EEE.toString();


回答3:

You could probably use eval on the string if you are looking to execute an operation on that path, but eval is pretty dangerous since it allows arbitrary code execution. If you want to JSON stringify the entire structure, there is JSON.stringify which is a standard feature in most new browsers and Doug Crockford has his own take on it for older browsers here.