Ctfrancia
Ctfrancia

Reputation: 1588

Angular 8 JSON.parse not parsing completely/impartially

I receive a JSON object that looks like this: this data is being passed through a Socketio emit, so the angular HttpClient is not intercepting it.

{
  "single":[
    {
      "name":"Xavi555",
      "data":[
        {
          "_id":"5e2ea609f8c83e5435ebb6e5",
          "id":"test1",
          "author":"someone",
          "recipient":"someone",
          "content":"test",
          "msgId":"Testid",
          "gNamespace":""
        }
      ]
    }
  ],
  "group":[]
}

however when I use JSON.parse() on the object above The key data does not contain the value of data that is to say:

private func(jsonObj: string): void {
  console.log(jsonObj);
}

I see:

single: Array(1)
groups: Array(0)
single Array(1)
  name: test
  data: Array(0)

I thought it was an issue with deep cloning, but, when trying to do JSON.parse(JSON.stringify(jsonObj)) it returns the original json string object. related but no solution posted

screen shot actual code:

private handleStoredMessages(dirtyObj: string): void {
  // debugger;
  const cleanObj = JSON.parse(dirtyObj);
   const { single, group } = cleanObj;

   console.log('raw json', dirtyObj);
   onsole.log('clean json', cleanObj);
}

any ideas?

Upvotes: 0

Views: 600

Answers (2)

Ctfrancia
Ctfrancia

Reputation: 1588

The issue of this was that the back end guy double encoded and did some weird stuff not my fault

Upvotes: 0

Poul Kruijt
Poul Kruijt

Reputation: 71961

If you are using angular, then I doubt you should be using JSON.parse. This is handled by the HttpClient. Nevertheless, your assumption about your data structure is wrong. The single is an array of objects, not an object itself:

So to access the .data you need to do jsonObj.single[0].data. Which in itself is an array again


The only other reason this could happen, is because you modify the object/array somewhere else in your code, before you actually press the triangle in console to open the object. Hover on the blue information icon to see why.

Value below was evaluated just now

The object is lazily evaluated, meaning that if you did any transformations to the object, it will show that state, not the state at the moment you logged the object.

Upvotes: 1

Related Questions