On the outermost level, a JSON object starts with a { and end with a }.
Sample data:
{
"cars": {
"Nissan": [
{"model":"Sentra", "doors":4},
{"model":"Maxima", "doors":4},
{"model":"Skyline", "doors":2}
],
"Ford": [
{"model":"Taurus", "doors":4},
{"model":"Escort", "doors":4}
]
}
}
If the JSON is assigned to a variable called data, then accessing it would be like the following:
data.cars['Nissan'][0].model // Sentra
data.cars['Nissan'][1].model // Maxima
data.cars['Nissan'][2].doors // 2
for (var make in data.cars) {
for (var i = 0; i < data.cars[make].length; i++) {
var model = data.cars[make][i].model;
var doors = data.cars[make][i].doors;
alert(make + ', ' + model + ', ' + doors);
}
}
Another approach (using an associative array for car models rather than an indexed array):
{
"cars": {
"Nissan": {
"Sentra": {"doors":4, "transmission":"automatic"},
"Maxima": {"doors":4, "transmission":"automatic"}
},
"Ford": {
"Taurus": {"doors":4, "transmission":"automatic"},
"Escort": {"doors":4, "transmission":"automatic"}
}
}
}
data.cars['Nissan']['Sentra'].doors // 4
data.cars['Nissan']['Maxima'].doors // 4
data.cars['Nissan']['Maxima'].transmission // automatic
for (var make in data.cars) {
for (var model in data.cars[make]) {
var doors = data.cars[make][model].doors;
alert(make + ', ' + model + ', ' + doors);
}
}
Edit:
Correction: A JSON object starts with { and ends with }, but it's also valid to have a JSON array (on the outermost level), that starts with [ and ends with ].
Also, significant syntax errors in the original JSON data have been corrected: All key names in a JSON object must be in double quotes, and all string values in a JSON object or a JSON array must be in double quotes as well.
See:
- JSON specification
- JSONLint - The JSON validator
On the outermost level, a JSON object starts with a { and end with a }.
Sample data:
{
"cars": {
"Nissan": [
{"model":"Sentra", "doors":4},
{"model":"Maxima", "doors":4},
{"model":"Skyline", "doors":2}
],
"Ford": [
{"model":"Taurus", "doors":4},
{"model":"Escort", "doors":4}
]
}
}
If the JSON is assigned to a variable called data, then accessing it would be like the following:
data.cars['Nissan'][0].model // Sentra
data.cars['Nissan'][1].model // Maxima
data.cars['Nissan'][2].doors // 2
for (var make in data.cars) {
for (var i = 0; i < data.cars[make].length; i++) {
var model = data.cars[make][i].model;
var doors = data.cars[make][i].doors;
alert(make + ', ' + model + ', ' + doors);
}
}
Another approach (using an associative array for car models rather than an indexed array):
{
"cars": {
"Nissan": {
"Sentra": {"doors":4, "transmission":"automatic"},
"Maxima": {"doors":4, "transmission":"automatic"}
},
"Ford": {
"Taurus": {"doors":4, "transmission":"automatic"},
"Escort": {"doors":4, "transmission":"automatic"}
}
}
}
data.cars['Nissan']['Sentra'].doors // 4
data.cars['Nissan']['Maxima'].doors // 4
data.cars['Nissan']['Maxima'].transmission // automatic
for (var make in data.cars) {
for (var model in data.cars[make]) {
var doors = data.cars[make][model].doors;
alert(make + ', ' + model + ', ' + doors);
}
}
Edit:
Correction: A JSON object starts with { and ends with }, but it's also valid to have a JSON array (on the outermost level), that starts with [ and ends with ].
Also, significant syntax errors in the original JSON data have been corrected: All key names in a JSON object must be in double quotes, and all string values in a JSON object or a JSON array must be in double quotes as well.
See:
- JSON specification
- JSONLint - The JSON validator
A good book I'm reading: Professional JavaScript for Web Developers by Nicholas C. Zakas 3rd Edition has the following information regarding JSON Syntax:
"JSON Syntax allows the representation of three types of values".
Regarding the one you're interested in, Arrays it says:
"Arrays are represented in JSON using array literal notation from JavaScript. For example, this is an array in JavaScript:
var values = [25, "hi", true];
You can represent this same array in JSON using a similar syntax:
[25, "hi", true]
Note the absence of a variable or a semicolon. Arrays and objects can be used together to represent more complex collections of data, such as:
{
"books":
[
{
"title": "Professional JavaScript",
"authors": [
"Nicholas C. Zakas"
],
"edition": 3,
"year": 2011
},
{
"title": "Professional JavaScript",
"authors": [
"Nicholas C.Zakas"
],
"edition": 2,
"year": 2009
},
{
"title": "Professional Ajax",
"authors": [
"Nicholas C. Zakas",
"Jeremy McPeak",
"Joe Fawcett"
],
"edition": 2,
"year": 2008
}
]
}
This Array contains a number of objects representing books, Each object has several keys, one of which is "authors", which is another array. Objects and arrays are typically top-level parts of a JSON data structure (even though this is not required) and can be used to create a large number of data structures."
To serialize (convert) a JavaScript object into a JSON string you can use the JSON object stringify() method. For the example from Mark Linus answer:
var cars = [{
color: 'gray',
model: '1',
nOfDoors: 4
},
{
color: 'yellow',
model: '2',
nOfDoors: 4
}];
cars is now a JavaScript object. To convert it into a JSON object you could do:
var jsonCars = JSON.stringify(cars);
Which yields:
"[{"color":"gray","model":"1","nOfDoors":4},{"color":"yellow","model":"2","nOfDoors":4}]"
To do the opposite, convert a JSON object into a JavaScript object (this is called parsing), you would use the parse() method. Search for those terms if you need more information... or get the book, it has many examples.
Videos
Hey, i am new to programming and I am trying to decode thousands of JSON files.
Usually there is one object in each JSON file, but for some reason a lot of my files have multiple JSON objects. Some have up to 5 objects.
{
"testNumber": "test200",
"device": {
"deviceID": 4000008
},
"user": {
"userID": "4121412"
}
}
{
"testNumber": "test201",
"device": {
"deviceID": 4000009
},
"user": {
"userID": "4121232"
}
}My code gives me the error: json.decoder.JSONDecodeError: Extra data: line 2 column 1
Because of that I am using except ValueError but I would like to get the data out of these JSON files.
import json
import os
test_dir = r'C:\Users\path\path'
for file in os.listdir(test_dir):
if 'testNumber' in file:
try:
data = json.load(open(test_dir + '\\' + file, 'r'))
print("valid")
except ValueError:
print("Decoding JSON has failed")Since json.loads and json.load don't work: is there any other way open the JSON file so that I can try to split the content in 2 objects?
This isn't a single JSON object. You have an array of JSON objects. You need to loop over array first and then access each object. Maybe the following kickoff example is helpful:
var arrayOfObjects = [{
"id": 28,
"Title": "Sweden"
}, {
"id": 56,
"Title": "USA"
}, {
"id": 89,
"Title": "England"
}];
for (var i = 0; i < arrayOfObjects.length; i++) {
var object = arrayOfObjects[i];
for (var property in object) {
alert('item ' + i + ': ' + property + '=' + object[property]);
}
// If property names are known beforehand, you can also just do e.g.
// alert(object.id + ',' + object.Title);
}
If the array of JSON objects is actually passed in as a plain vanilla string, then you would indeed need eval() here.
var string = '[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]';
var arrayOfObjects = eval(string);
// ...
To learn more about JSON, check MDN web docs: Working with JSON .
This is your dataArray:
[
{
"id":28,
"Title":"Sweden"
},
{
"id":56,
"Title":"USA"
},
{
"id":89,
"Title":"England"
}
]
Then parseJson can be used:
$(jQuery.parseJSON(JSON.stringify(dataArray))).each(function() {
var ID = this.id;
var TITLE = this.Title;
});
you are calling SaveProduct(BillNo, Pname, Pqty, Pcost);
after the for loop.so you are getting last index values.Make sure your method should be inside the loop.
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject2 = jsonArray.getJSONObject(i);
ProductName = jsonObject2.getString("product_name");
ProductQTY = jsonObject2.getString("product_quantity");
ProductCost = jsonObject2.getString("product_cost");
SaveProduct(BillNo, ProductName, ProductQTY, ProductCost);
}
So you need to make save call on your loop (json array length).
String BillNo = jo.optString("gstin_no");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject2 = jsonArray.optJSONObject(i);
String ProductName = jsonObject2.optString("product_name");
String ProductQTY = jsonObject2.optString("product_quantity");
String ProductCost = jsonObject2.optString("product_cost");
SaveProduct(BillNo, ProductName, ProductQTY, ProductCost);
}
Essentially what I've done is set up a JSON object containing two arrays:
var saveString = json_stringify(array1) + json_stringify(array2)
When I use the function json_parse to get them back, it only gives me the first array (array1). How can I call the second array from the json object?
Give this a try:
$json = '
{
"article_details":[
{
"article_code ":"000000000300028156 ",
"diff_amnt ":"1 "
},
{
"article_code ":"000000000300028174 ",
"diff_amnt ":"1 "
},
{
"article_code ":"000000000300028126 ",
"diff_amnt ":"1 "
}
],
"article":[
{
"article_code ":"000000000300028156 ",
"diff_amnt ":"1 "
},
{
"article_code ":"000000000300028174 ",
"diff_amnt ":"1 "
},
{
"article_code ":"000000000300028126 ",
"diff_amnt ":"1 "
}
]
}';
$key = 'article_code '; // Since your key is 'article_code ' but not 'article_code', I have to do this
$dataObject = json_decode($json);
echo $dataObject->article_details[0]->$key; // This will out put: 000000000300028156
$dataArray = json_decode($json, true);
echo $dataArray['article_details'][0]['article_code ']; // This will out put: 000000000300028156
Use json_decode() to decode a JSON string, like this:
$json_array = json_decode($json, true);
^ When TRUE, returned objects will be converted into associative arrays.
So your code should be like this:
// Here $json is your json string
$json_array = json_decode($json, true);
foreach($json_array as $key => $arrays){
echo $key . "<br />";
foreach($arrays as $array){
foreach($array as $key => $value){
echo $key . " => " . $value . "<br />";
}
}
echo "<br />";
}
Output:
article_details
article_code => 000000000300028156
diff_amnt => 1
article_code => 000000000300028174
diff_amnt => 1
article_code => 000000000300028126
diff_amnt => 1
article
article_code => 000000000300028156
diff_amnt => 1
article_code => 000000000300028174
diff_amnt => 1
article_code => 000000000300028126
diff_amnt => 1