javascript array to json code example

Example 1: js array to json

// Array to JSON:
const jsonString = JSON.stringify(yourArray);
// JSON to Object / Array
const yourData = JSON.parse(jsonString);

Example 2: turn object into string javascript

var obj = {a: "a", b: "b" /*...*/};
var string = JSON.stringify(obj);
// OUTPUT:
// "{'a':'a', 'b':'b'}"

Example 3: json php

//Json Encode

$person = array( 
    "name" => "KINGASV", 
    "title" => "CTO"
); 
$personJSON=json_encode($person);//returns JSON string

//Json Decode

$personJSON = '{"name":"KINGASV","title":"CTO"}';

$person = json_decode($personJSON);

echo $person->name; // KINGASV

Example 4: how to convert array to string json

var arr = [ "John", "Peter", "Sally", "Jane" ];
var myJSON = JSON.stringify(arr);

Example 5: js json_encode pretty

var str = JSON.stringify(obj, null, 2); // spacing level = 2

Example 6: Javascript object to JSON string

var person={"first_name":"Tony","last_name":"Hawk","age":31};
var personJSONString=JSON.stringify(person);

Tags: