How to parse a JSON and turn its values into an Array?
for your example:
{'profiles': [{'name':'john', 'age': 44}, {'name':'Alex','age':11}]}
you will have to do something of this effect:
JSONObject myjson = new JSONObject(the_json);
JSONArray the_json_array = myjson.getJSONArray("profiles");
this returns the array object.
Then iterating will be as follows:
int size = the_json_array.length();
ArrayList<JSONObject> arrays = new ArrayList<JSONObject>();
for (int i = 0; i < size; i++) {
JSONObject another_json_object = the_json_array.getJSONObject(i);
//Blah blah blah...
arrays.add(another_json_object);
}
//Finally
JSONObject[] jsons = new JSONObject[arrays.size()];
arrays.toArray(jsons);
//The end...
You will have to determine if the data is an array (simply checking that charAt(0)
starts with [
character).
Hope this helps.
How to parse json to get all values of a specific key within an array?
You cannot do contents[:]["name"]
since contents
is a list is a dictionary with integer indexes, and you cannot access an element from it using a string name
.
To fix that, you would want to iterate over the list and get the value for key name
for each item
import json
contents = []
try:
with open("./simple.json", 'r') as f:
contents = json.load(f)
except Exception as e:
print(e)
li = [item.get('name') for item in contents]
print(li)
The output will be
['Bulbasaur', 'Ivysaur']
How to convert JSON object to JavaScript array?
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/
Javascript how to parse JSON array
Javascript has a built in JSON parse for strings, which I think is what you have:
var myObject = JSON.parse("my json string");
to use this with your example would be:
var jsonData = JSON.parse(myMessage);
for (var i = 0; i < jsonData.counters.length; i++) {
var counter = jsonData.counters[i];
console.log(counter.counter_name);
}
Here is a working example
EDIT: There is a mistake in your use of for loop (I missed this on my first read, credit to @Evert for the spot). using a for-in loop will set the var to be the property name of the current loop, not the actual data. See my updated loop above for correct usage
IMPORTANT: the JSON.parse
method wont work in old old browsers - so if you plan to make your website available through some sort of time bending internet connection, this could be a problem! If you really are interested though, here is a support chart (which ticks all my boxes).
TypeScript - how to parse JSON array into array of custom objects
@Jaromanda X is correct- you are looking for JSON.parse
. Something like this would suffice:
responseArray = "[{"id":"blah", "type":"blah", ...}, {"id":"blah2",.... },...]"
<Item[]> JSON.parse(responseArray)
Obviously, this doesn't do any validation of the response (which is bad practice). You should ideally perform some validation of the result:
responseArray = "[{"id":"blah", "type":"blah", ...}, {"id":"blah2",.... },...]"
var result;
try {
itemListResponse = <Item[]>JSON.parse(responseArray);
if(!itemListResponse.has("id") ||
!itemListResponse.has("type") ||
!itemListResponse.has("state")){
throw "Invalid Item";
}
} catch (e){
}
Or, alternatively, use a JSON Schema validator like ajv.
How to parse a JSONArray and convert in Javascript
In order to convert all numeric values this will suffuce:
var data = [{"COMPLIANCE_ID":"1/FIRST/US/191CC2/20160906/pW1WSpD/1","TOLERANCE":null,"WEIGHTED_ARR_LAST_SLP":"0.03801186624130076","SLIPPAGE_INTERVAL_VWAP_BPS":"10.2711","ROOT_ORDER_ID":"735422197553491","ENTERING_TRADER":"duffy_dma2","SECURITY_ID":"EOG.N","ARRIVAL_MID_PX":"93.6100","WEIGHTED_ARR_SLP":"0.12323190317127024","AVG_PX":"93.6586","ORDER_CCY":"USD","LEAVES_QTY":"0","WEIGHT":"0.02372627566400397","INITIATING_TRADER":null,"PARTICIPATION_RATE":"0E-12","LOCAL_REF_END_TIME":"2016-09-06 06:00:27.775","WEIGHTED_IVWAP_SLP":"0.2436949499725512","NOTIONAL_USD":"477940","LIST_ID":null,"SYM":"EOG","LIQ_CONSUMPTION":"15.21","URGENCY":null,"SIDE":"Sell Short","ALGO":"Hydra","EXECUTING_TRADER":"duffy_dma2","EXEC_QTY":"5103","CL_ORD_ID":"7245294057012908344","LOCAL_REF_START_TIME":"2016-09-06 05:59:57.844","SLIPPAGE_END_LAST_ARR_LAST_BPS":"1.6021","ORD_STATUS":"Filled","IVWAP_PX":"93.5625","LIMIT_PX":"93.6100","ORDER_ID":"735422197553491","VOLUME_LIMIT":"0E-12","SLIPPAGE_ARR_MID_BPS":"5.1939","ORDER_QTY":"5103","CLIENT_ACRONYM":"PEAKM","EXECUTION_STYLE":"2"},{"COMPLIANCE_ID":"1/FIRST/US/191CC2/20160906/pW1PUxP/1","TOLERANCE":null,"WEIGHTED_ARR_LAST_SLP":"-0.046488357264395964","SLIPPAGE_INTERVAL_VWAP_BPS":"0.1625","ROOT_ORDER_ID":"73855219760798","ENTERING_TRADER":"duffy_dma2","SECURITY_ID":"MCD.N","ARRIVAL_MID_PX":"118.0950","WEIGHTED_ARR_SLP":"-0.0041198933937856425","AVG_PX":"118.0923","ORDER_CCY":"USD","LEAVES_QTY":"0","WEIGHT":"0.01830250285999841","INITIATING_TRADER":null,"PARTICIPATION_RATE":"0E-12","LOCAL_REF_END_TIME":"2016-09-06 05:32:24.895","WEIGHTED_IVWAP_SLP":"0.002974156714749742","NOTIONAL_USD":"368684","LIST_ID":null,"SYM":"MCD","LIQ_CONSUMPTION":"62.82","URGENCY":null,"SIDE":"Sell","ALGO":"Hydra","EXECUTING_TRADER":"duffy_dma2","EXEC_QTY":"3122","CL_ORD_ID":"7244573979975932119","LOCAL_REF_START_TIME":"2016-09-06 05:32:19.697","SLIPPAGE_END_LAST_ARR_LAST_BPS":"-2.5400","ORD_STATUS":"Filled","IVWAP_PX":"118.0904","LIMIT_PX":"117.9900","ORDER_ID":"73855219760798","VOLUME_LIMIT":"0E-12","SLIPPAGE_ARR_MID_BPS":"-0.2251","ORDER_QTY":"3122","CLIENT_ACRONYM":"PEAKM","EXECUTION_STYLE":"4"}]
function isNumeric(n) {
return !isNaN(parseFloat(n)) && isFinite(n);
}
var parsedData = data.map(function(obj) {
return Object.keys(obj).reduce(function(memo, key) {
var value = obj[key];
memo[key] = isNumeric(value) ? Number(value) : value;
return memo;
}, {})
})
console.log(parsedData);
Java - Parse JSON Array of Strings into String Array
So I ended up getting it to work with these changes! I had never worked with JSON before this project and apparently I had it written wrong for what I was trying to do.
JSONParser jsonParser2 = new JSONParser();
try (FileReader reader = new FileReader("Locations.json")) {
Object obj = jsonParser2.parse(reader);
JSONArray locationsList = (JSONArray) obj;
//Iterate over locations array
locationsList.forEach(emp -> parseJSONLocations((JSONObject) emp, locations, objects));
} catch (FileNotFoundException e) {
System.out.println(e);
} catch (IOException | ParseException e) {
System.out.println(e);
}
and then the method to add it all to a class was changed as such:
private static void parseJSONLocations(JSONObject locations, Locations[] location, Objects[] object) {
JSONObject locationObject = (JSONObject) locations.get("locations");
String desc = (String) locationObject.get("description");
String name = (String) locationObject.get("name");
JSONArray objects = (JSONArray) locationObject.get("objects");
Iterator<String> it = objects.iterator();
List<Objects> objs = new ArrayList<>();
while (it.hasNext()) {
String mStr = it.next();
for (Objects elm : object) {
if (elm.getName().equals(mStr)) {
objs.add(elm);
}
}
}
JSONArray directions = (JSONArray) locationObject.get("directions");
Map<String, String> map = new HashMap<>();
Iterator<JSONObject> it2 = directions.iterator();
while (it2.hasNext()) {
JSONObject value = it2.next();
map.put((String) value.get("direction"), (String) value.get("location"));
}
location[index2] = new Locations(desc, name, objs, map);
index2++;
}
But then I also had to change my JSON code, per jgolebiewski's suggestion:
[
{
"locations": {
"description": "You look around the room and see you are in an empty room with 2 doors to the left and to the right. Knowing not how you got there, you decide to figure out how to escape and get back to your normal life.",
"name": "start",
"objects": [],
"directions": [{
"direction": "right",
"location": "empty room1"
}, {
"direction": "left",
"location": "dungeon"
}]
}
},
{
"locations": {
"description": "Inside this room it looks like some sort of dungeon with a cage in the middle and blood lining the wall and floor.",
"name": "dungeon",
"objects": ["map", "torch"],
"directions": [{
"direction": "up",
"location": "hallway2"
}, {
"direction": "down",
"location": "hallway1"
}, {
"direction": "right",
"location": "start"
}]
}
}
]
Thank you for this tutorial for helping as well: https://howtodoinjava.com/library/json-simple-read-write-json-examples/
Related Topics
Why Are Interface Variables Static and Final by Default
Selenium 2.53 Not Working on Firefox 47
Handling Passwords Used for Auth in Source Code
Eclipse 2021-09 Code Completion Not Showing All Methods and Classes
Converting Symbols, Accent Letters to English Alphabet
How to Use an Internet Time Server to Get the Time
What Does Java Option -Xmx Stand For
In Java, How to Write a String Literal Without Having to Escape Quotes
How to Split a Comma-Separated String
How to Start/Stop/Restart a Thread in Java
How to Change Jdk Version for an Eclipse Project
Memory Address of Variables in Java
Strange Floating-Point Behaviour in a Java Program
Copying Files from One Directory to Another in Java
Effective Gif/Image Color Quantization
How to Implement a Map with Multiple Keys
What Is the Equivalent Lambda Expression for System.Out::Println