Cutting_edge
Cutting_edge

Reputation: 1

Error while accessing json array stored in MySQL DB

In one of my sql table's row there's a column stores JSON array. I can retrieve it via node JS but when I try to do json array stuff I get errors all the time. My Json array is as follows in sql DB.

{ characters: [{ code: "45", col: "", rem: "" },{ code: "", col: "", rem: "" },{ code: "", col: "", rem: "" },{ code: "", col: "", rem: "" }]}

I tried like this after getting via async functions

console.log(result[0].init_characters)

Sure data shows. But when I try to do,

console.log(result[0].init_characters.characters[1].code)

it gives errors like '1' is not defined. How can I get 1st arrays 'code' which is '45'?

Tried several methods like below. STill no luck

const myJSON = JSON.stringify(tt); 
const obj = JSON.parse(myJSON);
console.log(obj.characters[1].code);

Still no luck

Edit:Code that retrievs data

await connection.query( charSessSearch_query, async (err, result) => { if (err) throw err; console.log("------> done Results 1"); console.log(result.length); var tt = result[0].init_characters; const myJSON = JSON.stringify(tt); const obj = JSON.parse(myJSON); )

Yes this is mysql

Upvotes: 0

Views: 210

Answers (1)

Soso
Soso

Reputation: 50

I want to let you know about 2 things.

  • Correctly, the json array should be like this in the sql db. now the format is a bit wrong I think.

{"characters":[{"code":"45","col":"","rem":""},{"code":"","col":"","rem":""},{"code":"","col":"","rem":""},{"code":"","col":"","rem":""}]}

  • And to get "45" as you want, the index should be "0" not "1"!

hope this would be helpful to you.

Upvotes: 0

Related Questions