In my JS code, i have string as
s = "{\"selector\":{\"owner\":\"tom\"}}"; // originally this is a query response
I want to extract the value of 'owner' which is tom in another variable, s1.
What would be the easiest way to do it?
To convert your data to an object use obj = JSON.parse(s)
Then obj.selector.owner Or
obj["selector"]["owner"] which is the recommended way to get JavaScript object values...
You are not selecting the right properties when accessing your response data. Also you do not need to use toString in JSON.parse. Because your response is already a string data.
You want to convert string data by using JSON.parse
Demo:
//Response # 1
let findOwner = "{\"selector\":{\"owner\":\"tom\"}}"
//Parse Data
let parseData = JSON.parse(findOwner)
console.log(parseData.selector.owner) //Tom
//Response # 2
let findOwner2 = "{\"response\":{\"colour\":\"black\",\"make\":\"Tesla\",\"model\":\"S\",\"owner\":\"Adriana\"}}"
//Parse Data
let parseData2 = JSON.parse(findOwner2)
console.log(parseData2.response.owner) //Adriana
You can use a function for this:
function get(path, obj) {
return path.split('.').reduce((acc, current) => acc && acc[current], obj)
}
const obj = "{\"selector\":{\"owner\":\"tom\"}}"
const parsed = JSON.parse(obj)
get('selector.owner', parsed) // return 'tom'
I am returning a json data to jquery using php. what i want is to access the keys inside the json. i followed a tutorial and used json stringify but im not able to access the keys.
json data :
[
{"id":"1","movie_name":"spiderman","releases_on":"20th August 2018"},
{"id":"2","movie_name":"batman","releases_on":"21st August 2018"},
{"id":"3","movie_name":"fast and furious 6","releases_on":"22nd August 2018"}
]
code in jquery:
var json = data;
var obj = JSON.stringify(json);
console.log(obj[1].id);
you have to use JSON.parse(json).
then, you can do it.
JSON.stringify() will take your JSON object and convert it to a JSON string (here which is response).
JSON.parse() will take stringified JSON and convert it to object so that you can access via . operator
for example,
var a = { name: "John", age: 20 }
console.log(typeof a) // object
var out = JSON.stringify(a)
console.log(typeof out) // string
var res = JSON.parse(out)
console.log(typeof res) // object
I hope you got it....
I have a string with values i want to use. I'm parsing this string as an JSON object using $.parseJSON. However I'm having problems getting the actual values.
In this case I'm trying to get the value of the key "textarea1" which is "banana". What is the correct syntax for getting the values. I tried obj.texts.textarea1, but it didn't work.
The string looks like this:
var obj = "[{\"texts\":[{\"default\":true,\"bread-texts\":false,\"textarea1\":\"Banana\",\"textarea2\":\"Kiwi\",\"textarea3\":\Apple\",\"textarea4\":\"coffe\",\"textarea5\":\"Tea\",\"signature\":true,\"profile\":\"header\",\"fontsize\":\"26\",\"fontsize-headers\":\"10.5\",\"fontcolor\":\"#0000\",\"textfont\":\"header-large\",\"textsub1\":\"Bold\",\"font\":\"ICA%20Text\",\"textsub\":\"Regular\",\"textsize\":\"20\",\"textsize-signature\":\"9.5\",\"textsizesmall\":\"5.5\",\"textsizesmall-placer\":\"2.75\",\"vers-placer\":\"false\",\"text-colored\":\"%23000000\",\"s-all-customers\":true,\"new-customers\":true,\"undefined\":\"\"}]}]";
Script:
var oldVal = $.parseJSON(obj);
missing quote on \Apple
You access obj but need to access oldVal
you have nested arrays so you need array notation to get at them or flatten the arrays
You do not need jQuery and likely have not defined it. JSON.parse will work
var obj = "[{\"texts\":[{\"default\":true,\"bread-texts\":false,\"textarea1\":\"Banana\",\"textarea2\":\"Kiwi\",\"textarea3\":\"Apple\",\"textarea4\":\"coffe\",\"textarea5\":\"Tea\",\"signature\":true,\"profile\":\"header\",\"fontsize\":\"26\",\"fontsize-headers\":\"10.5\",\"fontcolor\":\"#0000\",\"textfont\":\"header-large\",\"textsub1\":\"Bold\",\"font\":\"ICA%20Text\",\"textsub\":\"Regular\",\"textsize\":\"20\",\"textsize-signature\":\"9.5\",\"textsizesmall\":\"5.5\",\"textsizesmall-placer\":\"2.75\",\"vers-placer\":\"false\",\"text-colored\":\"%23000000\",\"s-all-customers\":true,\"new-customers\":true,\"undefined\":\"\"}]}]";
var oldVal = JSON.parse(obj);
console.log(oldVal[0].texts[0].textarea1)
If you want to access oldVal.texts.textarea1 you need to remove the array:
var obj = "{\"texts\":{\"default\":true,\"bread-texts\":false,\"textarea1\":\"Banana\",\"textarea2\":\"Kiwi\",\"textarea3\":\"Apple\",\"textarea4\":\"coffe\",\"textarea5\":\"Tea\",\"signature\":true,\"profile\":\"header\",\"fontsize\":\"26\",\"fontsize-headers\":\"10.5\",\"fontcolor\":\"#0000\",\"textfont\":\"header-large\",\"textsub1\":\"Bold\",\"font\":\"ICA%20Text\",\"textsub\":\"Regular\",\"textsize\":\"20\",\"textsize-signature\":\"9.5\",\"textsizesmall\":\"5.5\",\"textsizesmall-placer\":\"2.75\",\"vers-placer\":\"false\",\"text-colored\":\"%23000000\",\"s-all-customers\":true,\"new-customers\":true,\"undefined\":\"\"}}";
1st Option
You need not to change anything. Just fix your JSON in correct format.
You can use JsonLint to check your JSON is correct or not. Then Proceed further.
var obj = "[{\"texts\":[{\"default\":true,\"bread-texts\":false,\"textarea1\":\"Banana\",\"textarea2\":\"Kiwi\",\"textarea3\":\"Apple\",\"textarea4\":\"coffe\",\"textarea5\":\"Tea\",\"signature\":true,\"profile\":\"header\",\"fontsize\":\"26\",\"fontsize-headers\":\"10.5\",\"fontcolor\":\"#0000\",\"textfont\":\"header-large\",\"textsub1\":\"Bold\",\"font\":\"ICA%20Text\",\"textsub\":\"Regular\",\"textsize\":\"20\",\"textsize-signature\":\"9.5\",\"textsizesmall\":\"5.5\",\"textsizesmall-placer\":\"2.75\",\"vers-placer\":\"false\",\"text-colored\":\"%23000000\",\"s-all-customers\":true,\"new-customers\":true,\"undefined\":\"\"}]}]";
var oldVal = JSON.parse(obj);
alert(oldVal[0].texts[0].textarea1)
2nd Option
If you want to get the result like obj.texts.textarea1 then you'll have to change your data as following.
Format Your JSON
Remove all [ and ] from your json.
then do.
var a = '{"texts": {"default": true,"bread-texts": false,"textarea1": "Banana","textarea2": "Kiwi","textarea3": "Apple","textarea4": "coffe","textarea5": "Tea","signature": true,"profile": "header","fontsize": "26","fontsize-headers": "10.5","fontcolor": "#0000","textfont": "header-large","textsub1": "Bold","font": "ICA%20Text","textsub": "Regular","textsize": "20","textsize-signature": "9.5","textsizesmall": "5.5","textsizesmall-placer": "2.75","vers-placer": "false","text-colored": "%23000000","s-all-customers": true,"new-customers": true,"undefined": ""} }';
var obj = JSON.parse(a);
Then
obj.texts.textarea1;
You've created array in your JSON so for that you need to do array accessing.
obj is of type string. You can not index it as object in the form obj.texts. You are parsing it using $.parseJSON, then use the object returned by that call:
var oldVal = $.parseJSON( obj );
var value = oldVal[0].texts[0].textarea1;
Your JSON is invalid.
At this place, you are missing a quote:
\"textarea3\":\Apple\" (escaped)
"textarea3":Apple" (unescaped)
JSON parsing will fail at this point.
After fixing this typo, I can easily access your JSON items this way:
var obj = "[{\"texts\":[{\"default\":true,\"bread-texts\":false,\"textarea1\":\"Banana\",\"textarea2\":\"Kiwi\",\"textarea3\":\"Apple\",\"textarea4\":\"coffe\",\"textarea5\":\"Tea\",\"signature\":true,\"profile\":\"header\",\"fontsize\":\"26\",\"fontsize-headers\":\"10.5\",\"fontcolor\":\"#0000\",\"textfont\":\"header-large\",\"textsub1\":\"Bold\",\"font\":\"ICA%20Text\",\"textsub\":\"Regular\",\"textsize\":\"20\",\"textsize-signature\":\"9.5\",\"textsizesmall\":\"5.5\",\"textsizesmall-placer\":\"2.75\",\"vers-placer\":\"false\",\"text-colored\":\"%23000000\",\"s-all-customers\":true,\"new-customers\":true,\"undefined\":\"\"}]}]";
// using JSON.parse
document.body.innerHTML = JSON.parse(obj)[0].texts[0].textarea1;
// or using jQuery
document.body.innerHTML += $.parseJSON(obj)[0].texts[0].textarea1;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I have example :
var data = [{"name":"eric","age":"24"},{"name":"goulding","age":"23"}]
I want to convert jso above to json like this result :
[{name:"eric",age:24},{name:"goulding",age:23}]
Please give me advice.
You need to use JSON.parse with a reviver parameter:
var jsonString = '[{"name":"eric","age":"24"},{"name":"goulding","age":"23"}]';
// given a string value, returns the number representation
// if possible, else returns the original value
var reviver = function (key, value) {
var number = Number(value);
return number === number ? number : value;
};
// because the reviver parameter is provided,
// the parse process will call it for each key-value pair
// in order to determine the ultimate value in a set
var data = JSON.parse(jsonString, reviver);
When the reviver is called with reviver("name", "eric"), it returns "eric" because "eric" cannot be converted to a number. However when called with reviver("age", "24"), the number 24 is returned.
Meanwhile, as others already noted the literal [{"name":"eric","age":"24"},{"name":"goulding","age":"23"}] is not JSON, it is an array. But the string '[{"name":"eric","age":"24"},{"name":"goulding","age":"23"}]' represents a valid JSON formatted array object.
let data = [{"name":"eric","age":"24"},{"name":"goulding","age":"23"}]
This is JSON and in order to convert it to a JavaScript object (jso) we need to use parse. If we want to manipulate JSON, we convert JSON to JSO using JSON.parse.
let convertedToJSO = JSON.parse(data)
let data = [{name:"eric",age:24},{name:"goulding",age:23}]
And this is a JSO. If you want to print or save JSO, convert JSO to JSON using JSON.stringfy.
let convertedToJSO = JSON.stringfy(data)
I have a JSON object like this coming back as a server response.
{"names":["Kreisler","Kreisler","Kreisler"]}
I need this object as an array.
Any help?
Use JSON.parse():
var json = '{"names":["Kreisler","Kreisler","Kreisler"]}';
data = JSON.parse(json);
console.log(data['names']); // ["Kreisler", "Kreisler", "Kreisler"]
Considering that response data is in response variable, use this:
var names = response["names"];
var data = JSON.parse('{"names":["Kreisler","Kreisler","Kreisler"]}', function(k, v) {
console.log(k); // log the current property name, the last is "".
return v; // return the unchanged property value.
});
console.log(data.names[0]);
If you are using the json parameter in datatype and your callback argument is called response, then:
arrayThatINeed = response.names;