how to get required output from json stringify array - javascript

My array look like this after use this code -:
var array=xmlhttrequest.responseText;
console.log(array);
["{\"result\":{\"isvalid\":true,\"address\":\"3EL5SKSjEzFQDBmXA5JFbsZu48vKnNSdDH\",\"scriptPubKey\":\"a9148aa3d53255b44655f82d163f37ecb68057f2edf487\",\"ismine\":false,\"iswatchonly\":false,\"isscript\":true},\"error\":null,\"id\":\"curltest\"}\n"]
I want value of isvalid , how can i get this .

That's a strange response. It's a stringified array, and that array contains a single item, which is another stringified object. Here's one option:
const responseText = String.raw`["{\"result\":{\"isvalid\":true,\"address\":\"3EL5SKSjEzFQDBmXA5JFbsZu48vKnNSdDH\",\"scriptPubKey\":\"a9148aa3d53255b44655f82d163f37ecb68057f2edf487\",\"ismine\":false,\"iswatchonly\":false,\"isscript\":true},\"error\":null,\"id\":\"curltest\"}\n"]`;
const [ stringItem ] = JSON.parse(responseText);
const itemObj = JSON.parse(stringItem);
const isvalid = itemObj.result.isvalid;
console.log(isvalid);
Note: While testing like this, you have to use String.raw so that the single backslashes are interpreted as literal backslashes and not unnecessary escape characters

The whole thing is an array as you can see it is wrapped inside [ ]. The inner content is a string, so you need to JSON.parse to convert into an object. Here is how you will get it JSON.parse(myData[0]).result.isvalid
var myData = ["{\"result\":{\"isvalid\":true,\"address\":\"3EL5SKSjEzFQDBmXA5JFbsZu48vKnNSdDH\",\"scriptPubKey\":\"a9148aa3d53255b44655f82d163f37ecb68057f2edf487\",\"ismine\":false,\"iswatchonly\":false,\"isscript\":true},\"error\":null,\"id\":\"curltest\"}\n"];
console.log("Is Valid: "+JSON.parse(myData[0]).result.isvalid);

use JSON.parse:
var obj = JSON.parse(array);
but I would try and eliminate all the unnecessary chars before using string.replace:
var json = array.replace("\", "");

Related

Loading string to array of array

I am getting a set of arrays in string format which looks like
[49,16,135],[51,16,140],[50,18,150]
Now I need to save them in an array of arrays. I tried it like
let array = [];
let str = '[49,16,135],[51,16,140],[50,18,150]';
array = str.split('[]');
console.log(array);
but it is creating only one array including all string as an element while I need to have
array = [[49,16,135],[51,16,140],[50,18,150]]
Add array delimiters to each end of the string, then use JSON.parse:
const str = '[49,16,135],[51,16,140],[50,18,150]';
const json = '[' + str + ']';
const array = JSON.parse(json);
console.log(array);
You are splitting it incorrectly, in the example, it will only split of there is a [] in the string
You can create a valid JSON syntax and parse it instead like so,
let str = '[49,16,135],[51,16,140],[50,18,150]';
let array = JSON.parse(`[${str}]`);
console.log(array);
Another way you could achieve this is by using a Function constructor. This method allows you to "loosely" pass your array.
const strArr = "[49,16,135],[51,16,140],[50,18,150]",
arr = Function(`return [${strArr}]`)();
console.log(arr);

How to get values from JSON object

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>

Regex extract contents

So, I have the following data here:
{"screenName":"fubars","msgHash":"C5STUYqhjzNiP6LLVbPlTF3zYLVYXHrm","imgURL":null,"userColor":"#00a4a0","messageTime":"2:50 PM","messageDate":1442256635621,"accountType":"m","accountTypeID":"z2ZkdXqck-JO45hqXVXH","isModerator":"","badges":""
I've written some regex to extract strings, but if I search for example "screenName" it gets the "fubars" part and the rest of the string, I only want the "fubars" part...
code:
function extractSummary(iCalContent, what) {
eval("var rxm = /\""+what+"\": \"(.*)\"/g");
console.log(rxm);
setTimeout(function(){},1500);
var arr = rxm.exec(iCalContent);
return arr[1];
}
If you have some data in the form of a JSON string, you can use JSON.parse to convert it into a JSON object. You can then use dot or index property getters.
var jsonString = '{"screenName":"fubars","msgHash":"C5STUYqhjzNiP6LLVbPlTF3zYLVYXHrm"}';
var jsonObject = JSON.parse(jsonString);
console.log(jsonObject.screenName);
console.log(jsonObject['screenName']);
There's no need to use regexes here.

Parse JSON array from string

I want to convert the following string to an array
var string = '["YES","NO"]';
How do I do this?
use the global JSON.parse method
JSON.parse('["YES","NO"]'); // returns ["YES", "NO"]
You can also use the JSON.stringify method to write the array back to a string if thats how you are storing it.
JSON.stringify(["YES", "NO"]); // returns '["YES", "NO"]'
var str= '["YES","NO"]';
var replace= str.replace(/[\[\]]/g,'');
var array = replace.split(',');
Fiddle : http://jsfiddle.net/9amstq41/
You can also use $.parseJSON:
var string = '["YES","NO"]';
var array = $.parseJSON(string);

How do I extract JSON objects from a string and add them to an array?

I want to extract all JSON objects from a string randomly containing them and add them to an array.
Sample string:
"I was with {"name":"John"}{"name":"Anne"}{"name":"Daniel"} yesterday"`
how can i extract the JSON objects from this sample string?
One approach to this is to use the str.search(regexp) function to find all parts of it that fulfill the JSON regex found here. So you could write a function that searches over the string for regexp matches.
To actually extract the object from the string you could use these two functions for the regex and then loop over the string until all objects have been found.
var match = str.match(regex);
var firstIndex = str.indexOf(match[0]);
var lastIndex = str.lastIndexOf(match[match.length-1]);
var JSONobjects = [];
while( str.match(regex){
//extract the wanted part.
jsonObject = substr(str.indexOf(match[0],str.lastIndexOf(match[match.length1-]));
//remove the already found json part from the string and continue
str.splice(str.indexOf(match[0],str.indexOf(match[0] + jsonObject.length());
//parse the JSON object and add it to an array.
JSONobjects.push(JSON.parse(jsonObject));
}
var a = JSON.parse('{"name":"John"}');
a ==> Object {name: "John"}
var b = [];
b.push(a);

Categories