How could I parse this json-string? - javascript

I have a string:
[{"data1":"A"},{"data2":"B"},{"data3":"C"}]
I used jQuery to convert this string to json:
test_json = $.parseJSON('[{"data1":"A"},{"data2":"B"},{"data3":"C"}]');
I got 3 objects:
I don't know, how could i get the key and value in this string-json?
Or the format of string-json is wrong?

have you tried cycle thorough the parsed array?
var test_json = $.parseJSON('[{"data1":"A"},{"data2":"B"},{"data3":"C"}]');
for(var a=0;a<test_json.length;a++) {
var obj = test_json[a];
for(var idx in obj) {
console.log(idx, obj[idx]);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

It has parsed the JSON correctly and returned an array of objects. You could do the following to access the first item containing { data1: "A" }:
console.log(tessst[0])

Related

How to convert a string to object and loop in react

I have a object which I am getting from database
Note: The below array is the output of console.log(ansoptions);
[{id:1, option:"Yes"},{id:2, option:"No"},{id:3, option:"Other"}]
This initially is in datatype string. I want to convert it into array of objects and loop to get id and option values.
I have tried below code
var ansoptions = JSON.parse(JSON.stringify(props.answerOptions));
console.log(ansoptions);
Array.from(ansoptions, item => {
console.log(item);
})
For the console.log(item) I am getting the output as weird as below
[
{
i
d
:
1
,
o
p
and so on.....
How do I get it? Please help !!
Parse the JSON (a string), then just loop over the array that's created.
const json = '[{"id":1, "option":"Yes"},{"id":2, "option":"No"},{"id":3, "option":"Other"}]';
const arr = JSON.parse(json);
for (let obj of arr) {
console.log(obj.id, obj.option);
}

Parsing JSON under Array object

I have a simple JSON string, encapsulated in an array created using JSONArray and JSONObject form org.json in Java.
var outObjA = [{"LoginTime":"2018-02-14 08:51:48.0","User":"f00dl3","RemoteIP":"127.0.0.1"}];
I am trying to parse this in JavaScript. First I iterate over the array encapsulating the data using an `i" counter:
for(var i = 0; i < outObjA.length; i++) {
var jsonData = JSON.parse(outObjA[i]);
console.log(jsonData);
}
When I attempt to parse the JSON, I get an error:
SyntaxError: JSON.parse: unexpected character at line 1 column 2 of the JSON data
I built a try/catch into it and it returns an object:
for (var i = 0; i < outObjA.length; i++) {
var jsonData = null;
try {
jsonData = JSON.parse(outObjA[i]);
} catch (e) {
jsonData = outObjA[i];
}
console.log(jsonData);
}
Returned:
{
"LoginTime": "2018-02-14 08:51:48.0",
"User": "f00dl3",
"RemoteIP": "127.0.0.1"
}
This is valid JSON, is it not?
That's not a JSON string, it's a JavaScript array. To make it a JSON string, surround it with apostrophes, then you can parse it, and finally loop through it:
var outObjA = '[{"LoginTime":"2018-02-14 08:51:48.0","User":"f00dl3","RemoteIP":"127.0.0.1"}]';
var outObjA = JSON.parse(outObjA);
for (var i = 0; i < outObjA.length; i++) {
var jsonData = outObjA[i];
console.log(jsonData);
}
Or better, you can loop through it directly without parsing:
var outObjA = [{"LoginTime": "2018-02-14 08:51:48.0", "User": "f00dl3", "RemoteIP": "127.0.0.1"}];
for (var i = 0; i < outObjA.length; i++) {
var jsonData = outObjA[i];
console.log(jsonData);
}
This line is not necessary.
for(var i = 0; i < outObjA.length; i++) {
var jsonData = JSON.parse(outObjA[i]);
console.log(jsonData);
}
Because outObjA is a array type not json,it does not need parsing simply retrieve it and display it.
The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string. An optional reviver function can be provided to perform a transformation on the resulting object before it is returned, source.
To expand further take this example from Mozilla ,
var json = '{"result":true, "count":42}';
The reason why this needs parsing is because its a string type, the JSON.parse converts that string into a JSON object, thus making it accessible. like this,
obj = JSON.parse(json);
console.log(obj.count);
// expected output: 42
console.log(obj.result);
// expected output: tru
The only way your code would work is if you did this.
var outObjA = ['{"LoginTime":"2018-02-14 08:51:48.0","User":"f00dl3","RemoteIP":"127.0.0.1"}'];
This way the element at position zero is a string, not a JSON object.
To conclude, strings are not JSON.
JSON objects are surrounded by curly braces {}.
JSON objects are written in key/value pairs.
Keys must be strings, and values must be a valid JSON data type
(string, number, object, array, boolean or null).
Keys and values are separated by a colon.
Each key/value pair is separated by a comma.
you do not need parse for it is already json
you might use instead
var jsonData = outObjA[i];
console.log(jsonData['User']); // or any other key

jsonify an array of strings

I have an array in my database that is being stored in the following format
["size:medium","height:10cm"]
this is problematic to display in a table.
Is there any way that I can convert this into a Javascript object or a JSON string like this?
{"size":"medium","height":"10cm"
}
p.s:i know json.stringfy,json_encode.the thing is they have stored key value pair as one string
You can build an object with the elements of the array and the left part as key and the right part as value of the by : separated strings.
array object
--------------------------- ---------------------------
[ -> {
"size:medium", -> size: "medium",
"height:10cm" -> height: "10cm"
] -> }
var array = ["size:medium", "height:10cm"],
object = array.reduce(function (r, a) {
var t = a.split(':');
r[t[0]] = t[1];
return r;
}, {});
document.write('<pre>' + JSON.stringify(object, 0, 4) + '</pre>');
You can try something like this:
Note: Following code will make array of objects. I don't think {["size:medium", "height:10cm"]} is a valid object
(function() {
var styleArr = ["size:medium", "height:10cm", "font-size: 18px"];
var resultObject = {};
styleArr.forEach(function(item) {
var values = item.replace(/\"/g, '').split(':');
resultObject[values[0]] = values[1];
});
console.log(resultObject)
})()
In Javascript you can use JSON.parse(), in order to convert your array in Javascript Object.
In PHP Use : json_encode(text)
In JavaScript : JSON.parse(text)

Manipulate Json String Jquery

Supposed that I have this JSON STRING that is stored in a vairable:
{"name":"Joene Floresca"},{"name":"Argel "}
How can I make it
["Joene", "Argel"]
You mention you have a string. Use JSON.parse for that. Also, make sure it is an array. Afterwards, you can manually iterate through each object in the array and push the value
var str = '[{"name": "Joene Floresca"},{ "name": "Argel "}]';
var objA = JSON.parse(str);
var values = [];
for (var i = 0; i < objA.length; i++) {
for (var key in objA[i]) {
values.push(objA[i][key]);
}
}
console.log(values);
Assuming your JSON is an array, you can use map:
// Your JSON string variable
var jsonString = '[{"name":"Joene Floresca"},{"name":"Argel "}]';
// Parse the JSON to a JS Object
var jsObject = $.parseJSON(jsonString);
// Use map to iterate the array
var arr = $.map(jsObject, function(element) {
// Return the name element from each object
return element.name;
});
console.log(arr); // Prints ["Joene Floresca", "Argel "]
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
You can iterate over objects inside array and store the names in a second array.
var data = JSON.parse('[{"name":"Joene Floresca"},{"name":"Argel "}]');
var names = [];
data.forEach(function(model) {
names.push(model.name);
});
// names now contains ["Joene Floresca", "Argel"]
alert(names);

How to convert Javascript array to JSON string

I have an array called values which has this data
var values=new Array();
values.push("english":"http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav");
values.push("kannada":"http://www.test.in/audio_ivrs/sr_listfrenchMSTR001.wav");
When I do JSON.stringify(values) I get values with square brackets, but I need a JSON string a shown below with urllist appended at the first.
{
"urlList":{
"english":"http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav",
"kannada":"http://www.test.in/audio_ivrs/sr_listfrenchMSTR001.wav"
}
}
Your code as you've defined it will give you errors. This is not valid JavaScript; you can't create an array element like this.
values.push("english":"http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav");
If you want the structure you've specified in your question then you'll need to use a nested object rather than an array to contain the key/value pairs.
var values = {
urlList: {}
};
values.urllist.english = "http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav";
values.urllist.kannada = "http://www.test.in/audio_ivrs/sr_listfrenchMSTR001.wav";
DEMO
HOWEVER...
Let's assume for a moment that what you meant to code was this (note the curly braces):
var values=new Array();
values.push({"english":"http://www.test.in/audio_ivrs/sr_listenglishMSTR001.wav"});
values.push({"kannada":"http://www.test.in/audio_ivrs/sr_listfrenchMSTR001.wav"});
This would tell me that you're pushing objects into an array which is perfectly valid JavaScript.
To get this information from the array into the structure you need you can use something like this loop:
var out = {
urlList: {}
};
for (var i = 0, l = values.length; i < l; i++) {
var el = values[i];
var key = Object.keys(el);
var value = el[key];
out.urlList[key] = value;
}
JSON.stringify(out);
DEMO

Categories

Resources