I have a JSON file which has this:
[
{
"id":"1",
"customer":{
"nickname":"nick001",
"email":"",
"id":"15615",
"name":"Smith Dole",
"phone":"5555555"
},
"totalorder":"44155",
"items":[
{
"code":"041545420",
"title":"item",
"quantity":1,
"price":"2461.7500",
"subtotal":2461.75
}
]
}
]
As you can see it doesn´t have any parent root name. How can I read this JSON with JavaScript?
I was thinking to PARSE the Json but JSON.parse(need the name)
Is it possible to call this JSON in my JavaScript code and asign it a variable?
var newSelling = data from the JSON
The JSON is being generated by another system which generates it that way so I need to read the JSON to get the data needed for other processes
the JSON is automatically generated and it is in an external file
So it is a JSON file. Request it with fetch or XMLHttpRequest and access the JSON.
fetch('/path/to/your/file.json')
.then(response => response.json())
.then(data => {
console.log(data)
});
If you want to read the file in the Browser from your local you can use one of these solutions:
Axios .
I recommend Fetch API.
fetch("data.json")
.then(response => response.json())
.then(json => console.log(json));
It works in Firefox, but in Chrome you have to customize security setting.
If you look carefully, you'll see that this JSON file is just a JSON array with only one Object inside of it. So you have to access the object that is in the array.
let arr = JSON.parse(*the json object*);
let obj = arr[0];
I haven't tested this, but hopefully this helps.
Here in your case, using JSON.parse only is not working but the combination of JSON.stringify and JSON.parse is working as I tried. So first, we can stringify it and then we can parse it
Like this:
var a = [
{
"id":"1",
"customer":{
"nickname":"nick001",
"email":"",
"id":"15615",
"name":"Smith Dole",
"phone":"5555555"
},
"totalorder":"44155",
"items":[
{
"code":"041545420",
"title":"item",
"quantity":1,
"price":"2461.7500",
"subtotal":2461.75
}
]
}
];
var b = JSON.stringify(a);
var c = JSON.parse(b);
console.log(c[0].id); //output : 1
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.