Typically, a Json object would contain your values (including arrays) as named fields within. So, something like:
JSONObject jo = new JSONObject();
JSONArray ja = new JSONArray();
// populate the array
jo.put("arrayName",ja);
Which in JSON will be {"arrayName":[...]}.
Answer from david van brink on Stack OverflowTypically, a Json object would contain your values (including arrays) as named fields within. So, something like:
JSONObject jo = new JSONObject();
JSONArray ja = new JSONArray();
// populate the array
jo.put("arrayName",ja);
Which in JSON will be {"arrayName":[...]}.
I have JSONObject like this: {"status":[{"Response":"success"}]}.
If I want to convert the JSONObject value, which is a JSONArray into JSONObject automatically without using any static value, here is the code for that.
JSONArray array=new JSONArray();
JSONObject obj2=new JSONObject();
obj2.put("Response", "success");
array.put(obj2);
JSONObject obj=new JSONObject();
obj.put("status",array);
Converting the JSONArray to JSON Object:
Iterator<String> it=obj.keys();
while(it.hasNext()){
String keys=it.next();
JSONObject innerJson=new JSONObject(obj.toString());
JSONArray innerArray=innerJson.getJSONArray(keys);
for(int i=0;i<innerArray.length();i++){
JSONObject innInnerObj=innerArray.getJSONObject(i);
Iterator<String> InnerIterator=innInnerObj.keys();
while(InnerIterator.hasNext()){
System.out.println("InnInnerObject value is :"+innInnerObj.get(InnerIterator.next()));
}
}
How to convert a JSON array to a JSON object
Convert array to JSON - javascript
How to convert JSON object to JavaScript array? - Stack Overflow
Converting JSON array to objects
Script for backward-compatibility: https://github.com/douglascrockford/JSON-js/blob/master/json2.js
And call:
var myJsonString = JSON.stringify(yourArray);
Note: The JSON object is now part of most modern web browsers (IE 8 & above). See caniuse for full listing. Credit goes to: @Spudley for his comment below
I made it that way:
if I have:
var jsonArg1 = new Object();
jsonArg1.name = 'calc this';
jsonArg1.value = 3.1415;
var jsonArg2 = new Object();
jsonArg2.name = 'calc this again';
jsonArg2.value = 2.73;
var pluginArrayArg = new Array();
pluginArrayArg.push(jsonArg1);
pluginArrayArg.push(jsonArg2);
to convert pluginArrayArg (which is pure javascript array) into JSON array:
var jsonArray = JSON.parse(JSON.stringify(pluginArrayArg))
var json_data = {"2013-01-21":1,"2013-01-22":7};
var result = [];
for(var i in json_data)
result.push([i, json_data [i]]);
var data = new google.visualization.DataTable();
data.addColumn('string', 'Topping');
data.addColumn('number', 'Slices');
data.addRows(result);
http://jsfiddle.net/MV5rj/
If you have a well-formed JSON string, you should be able to do
var as = JSON.parse(jstring);
I do this all the time when transfering arrays through AJAX.
You can loop over the elements, and populate a new Object along the way:
var arr = [
{"id": "01", "state": "Alabama", "category": "Coal", "detail1": null, "detail2": null},
{"id": "02", "state": "Alaska", "category": null, "detail1": null, "detail2": null},
{"id": "04", "state": "Arizona", "category": "Oil", "detail1": null, "detail2": null}
];
// Here, I create a copy of the array to avoid modifying the original one.
var obj = {}, copy = JSON.parse( JSON.stringify(arr) );
for(var i in copy){
obj[ copy[i].id ] = copy[i]; // Add the element to obj, at index id
delete copy[i].id; // Remove the id from the inserted object
}
console.log(obj);
Looping over an array to create a new value typically uses reduce, which allows values to be accumulated in a value that can be passed along to the next invocation of the callback.
I'll assumed in this case that you just want a shallow copy of each member passed in with the id property removed and added to the new value, which can be an object:
var arr = [
{"id": "01", "state": "Alabama", "category": "Coal", "detail1": null, "detail2": null},
{"id": "02", "state": "Alaska", "category": null, "detail1": null, "detail2": null},
{"id": "04", "state": "Arizona", "category": "Oil", "detail1": null, "detail2": null}
]
// Loop over all numeric members of arr
var newStructure = arr.reduce(function(obj, v){
// Store the value of the ID property of the passed in object
var id = v.id;
// Remove the id property from the passed in object
delete v.id;
// Add the id value and remainder of the object to the accumulator
obj[id] = v;
// Return the accumulator
return obj;
},{});
document.write(JSON.stringify(newStructure));
Note that this modifies the original objects, the code to copy them instead isn't much longer.
If you have a JS array of JSON objects:
var s=['{"Select":"11","PhotoCount":"12"}','{"Select":"21","PhotoCount":"22"}'];
and you want an array of objects:
// JavaScript array of JavaScript objects
var objs = s.map(JSON.parse);
// ...or for older browsers
var objs=[];
for (var i=s.length;i--;) objs[i]=JSON.parse(s[i]);
// ...or for maximum speed:
var objs = JSON.parse('['+s.join(',')+']');
See the speed tests for browser comparisons.
If you have a single JSON string representing an array of objects:
var s='[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';
and you want an array of objects:
// JavaScript array of JavaScript objects
var objs = JSON.parse(s);
If you have an array of objects:
// A JavaScript array of JavaScript objects
var s = [{"Select":"11", "PhotoCount":"12"},{"Select":"21", "PhotoCount":"22"}];
…and you want JSON representation for it, then:
// JSON string representing an array of objects
var json = JSON.stringify(s);
…or if you want a JavaScript array of JSON strings, then:
// JavaScript array of strings (that are each a JSON object)
var jsons = s.map(JSON.stringify);
// ...or for older browsers
var jsons=[];
for (var i=s.length;i--;) jsons[i]=JSON.stringify(s[i]);
var json = jQuery.parseJSON(s); //If you have jQuery.
Since the comment looks cluttered, please use the parse function after enclosing those square brackets inside the quotes.
var s=['{"Select":"11","PhotoCount":"12"}','{"Select":"21","PhotoCount":"22"}'];
Change the above code to
var s='[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';
Eg:
$(document).ready(function() {
var s= '[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';
s = jQuery.parseJSON(s);
alert( s[0]["Select"] );
});
And then use the parse function. It'll surely work.
EDIT :Extremely sorry that I gave the wrong function name. it's jQuery.parseJSON
Jquery
The json api
Edit (30 April 2020):
Editing since I got an upvote for this answer. There's a browser native function available instead of JQuery (for nonJQuery users), JSON.parse("<json string here>")
You can use the deserialize method in Apex JSON class :
String jsonInput = [{"Attributes": {"Type":"Account","url";"/servicec/data/v4.0"},
"LastModified":"2017-05-05"}];
Map<String, Object> array = (Map<String, Object>) JSON.deserializeUntyped(jsonInput);
String firstElt = array[0];
The documentation is here.
List<Object> arr =(List<Object>)JSON.deserializeUntyped(jsonInput);
String firstemement = arr[0];