-5

I have the following JSON file:

({
    "text1": "item_1",
    "text2": "item_2",
    "text3": "item_3",
    "text4": "item_4"
})

How can I print the value of text2 ?

Do jQuery will be fastest than pure JS ?

Thanks a lot.

Lucky Chingi
  • 2,248
  • 1
  • 10
  • 15
Carotte
  • 1
  • 2
  • http://stackoverflow.com/questions/4935632/parse-json-in-javascript – Lucky Chingi Jan 19 '16 at 21:32
  • 3
    JSON cannot start with `(` – Gabriele Petrioli Jan 19 '16 at 21:32
  • @LuckyChingi, yes but how to load the json? Actually the json is into the variable. – Carotte Jan 19 '16 at 21:33
  • If you already have the json loaded in a variable the do `variablename.text2`. If it is in string format in the variable then parse it first with [`JSON.parse`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON`) – Gabriele Petrioli Jan 19 '16 at 21:39
  • @Carotte no framework is faster than pure JavaScript, because they all derive from JavaScript. – Jordan Davis Jan 19 '16 at 21:39
  • @Carotte if you are declaring the JSON object statically which looks to be the case then, wrap it in a ` – Jordan Davis Jan 19 '16 at 21:42

3 Answers3

1

Once that object is assigned to a variable (say foo) you'd be able to print text2 value by doing:

var foo = {
  "text1": "item_1",
  "text2": "item_2",
  "text3": "item_3",
  "text4": "item_4"
};

console.log(foo.text2);

Regarding how faster is JS over jQuery, this is a very simple instruction and there won't be a significant difference between one or the other.

Cristiano Mendonça
  • 1,220
  • 1
  • 10
  • 21
0

var strJSON = '{ "text1": "item_1", "text2": "item_2", "text3": "item_3", "text4": "item_4" }';

var objJSON = eval("(function(){return " + strJSON + ";})()");

alert(objJSON.text2);

Srini
  • 19
  • 4
-1
$.getJSON("test.json", function(json) {
    console.log(json); // this will show the info it in console
    console.log(json.text2); //should print item_2 in console   
});

pure JS is faster if you know how to write it properly. Jquery add a lot of nice features for developers but it costs CPU and memory.

This example above uses jQuery (hence the $)

MichaelWClark
  • 382
  • 1
  • 12
  • this is assuming your json file that you mentioned is test.json and in the same directory.... – MichaelWClark Jan 19 '16 at 21:36
  • 1
    Thanks. It helps me a lot. Do not why why someone -1 your answer. – Carotte Jan 19 '16 at 21:38
  • down, because jquery is not necessary for accessing an object – Nina Scholz Jan 19 '16 at 21:48
  • That wasn't the question. I provided an answer using the technologies he is using and then answered the 2nd question to the best of my ability. I'm well aware jQuery isn't required, I even advocated pure JS. For his needs this would suffice. If the answers are wrong then -1. – MichaelWClark Jan 19 '16 at 21:56