Parse Json in JavaScript

Parse JSON in JavaScript?

The standard way to parse JSON in JavaScript is JSON.parse()

The JSON API was introduced with ES5 (2011) and has since been implemented in >99% of browsers by market share, and Node.js. Its usage is simple:

const json = '{ "fruit": "pineapple", "fingers": 10 }';
const obj = JSON.parse(json);
console.log(obj.fruit, obj.fingers);

How to parse JSON to JSON in javascript?

This algorithm is pretty straightforward--something like the following should work:

function parse(a) {  //create object to return  var ret = {    columns: [],    data: []  };
//iterate the source array a.forEach(function(item, i) { if (i === 0) { //first time through, build the columns for (var key in item) { ret.columns.push(key); } }
//now build your data item ret.data[i] = [];
//use the column array to guarantee that the order of the fields in the source string doesn't matter for (var j = 0; j < ret.columns.length; j++) { var key = ret.columns[j]; ret.data[i].push(item[key]); } }); return ret;}
var j = { "d": "[{\"ID\":\"VN00000123\",\"NAME\":\"JOHN GREEN\",\"GENDER\":\"Male\",\"BIRTHDAY\":\"15-10-1987\"},{\"NAME\":\"MERRY BLUE\",\"BIRTHDAY\":\"03-12-1983\",\"ID\":\"VN00000456\",\"GENDER\":\"Female\"},{\"GENDER\":\"Male\",\"ID\":\"VN00000789\",\"NAME\":\"BLACK BROWN\",\"BIRTHDAY\":\"09-07-1990\"}]"};
//j is an object with one property (d) that is a JSON string that needs parsingvar o = parse(JSON.parse(j.d));console.log(o);

How to parse JSON string in Typescript

Typescript is (a superset of) javascript, so you just use JSON.parse as you would in javascript:

let obj = JSON.parse(jsonString);

Only that in typescript you can have a type to the resulting object:

interface MyObj {
myString: string;
myNumber: number;
}

let obj: MyObj = JSON.parse('{ "myString": "string", "myNumber": 4 }');
console.log(obj.myString);
console.log(obj.myNumber);

(code in playground)

Parse Json with javascript with for loop

You have some errors on the code you presented:

  1. Your data has Results, Variable and Value (and other properties also), all of them with uppercase first letter, and in your code you are trying to access it with lowercase (e.g: data.results), so it is undefined (Javascript is a case-sensitive language), it must be data.Results.

  2. Also, you are looping through Results, not Variable, so the [i] goes after Results, like this: data.Results[i].Variable

see below

var data = {  "Count": 136,  "Message": "Results returned successfully.",  "SearchCriteria": "VIN:xxxxxxx",  "Results": [{      "Value": "",      "ValueId": "",      "Variable": "Suggested VIN",      "VariableId": 142    },    {      "Value": "0",      "ValueId": "0",      "Variable": "Error Code",      "VariableId": 143    },    {      "Value": "",      "ValueId": "",      "Variable": "Possible Values",      "VariableId": 144    },    {      "Value": null,      "ValueId": "",      "Variable": "Additional Error Text",      "VariableId": 156    }  ]}

for (let i = 0; i < data.Results.length; i++) { if (data.Results[i].Variable == 'Error Code') { console.log(data.Results[i].Value); }}

Javascript how to parse JSON array

Javascript has a built in JSON parse for strings, which I think is what you have:

var myObject = JSON.parse("my json string");

to use this with your example would be:

var jsonData = JSON.parse(myMessage);
for (var i = 0; i < jsonData.counters.length; i++) {
var counter = jsonData.counters[i];
console.log(counter.counter_name);
}

Here is a working example

EDIT: There is a mistake in your use of for loop (I missed this on my first read, credit to @Evert for the spot). using a for-in loop will set the var to be the property name of the current loop, not the actual data. See my updated loop above for correct usage

IMPORTANT: the JSON.parse method wont work in old old browsers - so if you plan to make your website available through some sort of time bending internet connection, this could be a problem! If you really are interested though, here is a support chart (which ticks all my boxes).

How to parse JSON in node js

User is already a list of objects, so you don't need to parse it. However, it is an array. So if you meant for it to be an array, you'd need to access the password by using this code:

console.log(user[0].password);

How do I parse JSON sprinkled unpredictably into a string?

Here's a comparatively simple brute-force approach: split the whole input string on curly braces, then step through the array in order. Whenever you come across an open brace, find the longest chunk of the array from that starting point that successfully parses as JSON. Rinse and repeat.

This will not work if the input contains invalid JSON and/or unbalanced braces (see the last two test cases below.)

const tryJSON = input => {  try {    return JSON.parse(input);  } catch (e) {    return false;  }}
const parse = input => { let output = []; let chunks = input.split(/([{}])/);
for (let i = 0; i < chunks.length; i++) { if (chunks[i] === '{') { // found some possible JSON; start at the last } and backtrack until it works. for (let j = chunks.lastIndexOf('}'); j > i; j--) { if (chunks[j] === '}') { // Does it blend? let parsed = tryJSON(chunks.slice(i, j + 1).join("")) if (parsed) { // it does! Grab the whole thing and skip ahead output.push(parsed); i = j; } } } } else if (chunks[i]) { // neither JSON nor empty output.push(chunks[i]) } }
console.log(output) return output}
parse(`{"foo": "bar"}`)parse(`test{"foo": "b}ar{{[[[{}}}}{}{}}"}`)parse(`this {"is": "a st}ri{ng"} with {"json": ["in", "i{t"]}`)parse(`{}`)parse(`this {"i{s": invalid}`)parse(`So is {this: "one"}`)

Parse function inside Json

QUICK ANSWER:

The function bellow will do it:

function fix(obj){

for (var property in obj) {
if (obj.hasOwnProperty(property)) {
obj[property] = eval("(" + obj[property] + ")");
}
}

}

If obj has your JSON parsed object then just do the following:

fix(obj);
console.log(obj); // in case you want to see the change in the console

EXPLANATION (IF YOU NEED ONE):

You will be able to get the javascript function expression if you enclose the string with parentheses '()' before invoking eval.

So the steps to achieve the desired result are:

  1. Enclose the function expression string in parentheses (see footnotes for the reason why)
  2. Invoke the eval function to evaluate the function declaration expression
  3. Assign the function declaration expression to the same property that contained the string value

For the simplistic example you gave, you can get the desired results by:

var obj = {"get":"function (f,g){'use strict';var h,i;if(i={},'string'==typeof f){if('object'==typeof g)for(h in g)i[h]=g

[h];i.url=f}else if('object'==typeof f)for(h in f)i[h]=f[h];return i.type=i.type||d,i.oauthio=

{provider:a,tokens:b,request:c},e.http(i)}","post":"function (f,g){'use strict';var h,i;if(i={},'string'==typeof f){if

('object'==typeof g)for(h in g)i[h]=g[h];i.url=f}else if('object'==typeof f)for(h in f)i[h]=f[h];return i.type=i.type||

d,i.oauthio={provider:a,tokens:b,request:c},e.http(i)}"};

obj.get = eval("(" + obj.get + ")");
obj.post = eval("(" + obj.post + ")");

You can automate that by using the following function:

function fix(obj){

for (var property in obj) {
if (obj.hasOwnProperty(property)) {
obj[property] = eval("(" + obj[property] + ")");
}
}

}

Your final code should be something like:

function fix(obj){

for (var property in obj) {
if (obj.hasOwnProperty(property)) {
obj[property] = eval("(" + obj[property] + ")");
}
}

}


var obj = {"get":"function (f,g){'use strict';var h,i;if(i={},'string'==typeof f){if('object'==typeof g)for(h in g)i[h]=g

[h];i.url=f}else if('object'==typeof f)for(h in f)i[h]=f[h];return i.type=i.type||d,i.oauthio=

{provider:a,tokens:b,request:c},e.http(i)}","post":"function (f,g){'use strict';var h,i;if(i={},'string'==typeof f){if

('object'==typeof g)for(h in g)i[h]=g[h];i.url=f}else if('object'==typeof f)for(h in f)i[h]=f[h];return i.type=i.type||

d,i.oauthio={provider:a,tokens:b,request:c},e.http(i)}"};

fix(obj);

Footnotes:

In case you have interest to know why the parentheses are needed please check the link below:

Why does JavaScript's eval need parentheses to eval JSON data?



Related Topics



Leave a reply



Submit