Shabeer Mothi
Shabeer Mothi

Reputation: 137

How to create a json programatically with Javascript

I am trying to read from database a set of values and i would like to construct it as JSON with Javascript. Is there a way i can do it. I do not want to simply have it appended as String in JAvascript.

Can anybody please help me out ?

Upvotes: 0

Views: 113

Answers (4)

Shabeer Mothi
Shabeer Mothi

Reputation: 137

Found the solution. I created a Javascript string which would be constructed in the form of JSON. The after iterating through the source json and creating string in target json format i used JSON.stringify to convert it to JSON. Worked well.

Thanks for all replies.

Upvotes: 0

jingyinggong
jingyinggong

Reputation: 646

what's your backend language? for most of the languages will provide a function called jsonEncode() you may try this.

take php for example

<?php
$yourphparray = array(
    "key1"=> "value1",
    "key2"=> "value2",
    "key3"=> "value3"
);
echo json_encode($yourphparray); 
?>

you may get the json like this

{ "key1": "value1", "key2": "value2", "key3": "value3" }

if you just return as a string, you may have to use the json2.js by Douglas Crockford; the json2.js provid a function

jsondecode(yourstring); 

to make a string to a js object!

Upvotes: 1

Edgar Villegas Alvarado
Edgar Villegas Alvarado

Reputation: 18354

With this method

var jsonString = JSON.stringify(any_object_or_array);

Hope this helps. Cheers

PS: Read from database and store it to json in js... I assume you're with nodeJs

Upvotes: 0

TGH
TGH

Reputation: 39268

Just build a javascript object

var myJsonObj = {name:"Some Value"};

If you need it in string format you can do the following:

JSON.stringify(myJsonObj);

Upvotes: 1

Related Questions