{
"name":"John",
"age":31,
"pets":[
{ "dog","cat","pug" }
]
"cars":[
{ "bmw","Ferrari","fiat" }
]
}
If not possible to store in this format.How do i store this kind of data in a .json file and access it?
{
"name":"John",
"age":31,
"pets":[
{ "dog","cat","pug" }
]
"cars":[
{ "bmw","Ferrari","fiat" }
]
}
If not possible to store in this format.How do i store this kind of data in a .json file and access it?
In your case, you should decode your Json, store it in a variable twith the following code :
var data = JSON.parse(yourJson);
and you can read it with
data["name"]
for example.
Hope I helped you !
EDIT : I agree with the others, your JSON is not valid, but when your JSON is ok, my method should work
If you have a file: data.json - containing valid json text:
{
"name": "John",
"age": 31,
"pets": ["dog","cat","pug"],
"cars": ["BMW","Ferrari","Nissan"],
"wife": {"name":"Jane","age":"27"},
"children":[{"name":"Jack","age":"10"},{"name":"Jill","age":"6"}]
}
you will need a web server like mongoose to run the page in - to access the file on your hard drive and not get a cross origin error: https://www.cesanta.com/products/binary
using test.html file:
<html>
<body>
hello - key f12 in browser to view console output
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$.getJSON('data.json', function(_jsonData)
{
console.log(_jsonData); // output json to console - f12 in browser to view (I recommend Chrome)
console.log(_jsonData.name); // output: John
console.log(_jsonData.age); // output: 31
console.log(_jsonData.pets[1]); // output: cat
console.log(_jsonData.cars[3]); // output: Nissan
console.log(_jsonData.wife.name); // output: Jane
console.log(_jsonData.children[1].name); // output: Jill
})
.done(function()
{
console.log("success");
})
.fail(function(e)
{
console.log("error: ", e);
})
.always(function() {
console.log("complete");
});
</script>
</body>
</html>
or you can look at the fiddle which doesn't access a file but has the json defined in the js...
var jsonData =
{
"name": "John",
"age": 31,
"pets": ["dog","cat","pug"],
"cars": ["BMW","Ferrari","Nissan"],
"wife": {"name":"Jane","age":"27"},
"children":[{"name":"Jack","age":"10"},{"name":"Jill","age":"6"}]
}
$('#divOutput').html(
'json: ' + JSON.stringify(jsonData) + '<br><br>' +
'name: ' + jsonData.name + '<br>' + // output: John
'age: ' + jsonData.age + '<br>' + // output: 31
'2nd pet: ' + jsonData.pets[1] + '<br>' + // output: cat
'3rd car: ' + jsonData.cars[2] + '<br>' + // output: Nissan
"wife's name: " + jsonData.wife.name + '<br>' + // output: Jane
"second child's name: " + jsonData.children[1].name); // output: Jill
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="divOutput"></div>