0

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

5 Answers5

1

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)
  });
epascarello
  • 204,599
  • 20
  • 195
  • 236
1

If you want to read the file in the Browser from your local you can use one of these solutions :

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.

-1

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.

-1

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
jahnavi13
  • 42
  • 4
-2

Parsing JSON should work as follows:

const json = '{"result":true, "count":42}';
const obj = JSON.parse(json);

console.log(obj.count);
// expected output: 42

console.log(obj.result);
// expected output: true

More info

Edit: You can red this question. I think it may help